Bash Script to Create a Virtualmin Server and Transfer Files and Database from Another Server

We needed to move many sites from one server to a Virtualmin server, so created a simple script that:-

  1. Connects to the Virtualmin server and creates the new account
  2. Connects to the source server via SSH to then copy the source files and database to the destination Virtualmin server
  3. Imports the database on the destination server

All that is left is update config files on the destination server and it’s complete. It dramatically speeds up moving websites to Virtualmin servers. It can be used without the Virtualmin part, just to copy files and databases. 

This script is designed to sit on a main computer, and connect to the source and destination computers. A little tweaking and you could just put on the source or destination servers itself. 

 

# http://www.virtualmin.com/documentation/developer/cli

set -e

# New Site Settings #
site_domain="your-domain.co.uk"

# Source Server Details #
source_server="your-source-server.co.uk"
source_username="account-name"
source_db="account-database"

# Destination Server Details #
dest_server="your-destination-server.co.uk"
dest_username="account-name"
dest_db="account-db"
dest_pass="xxxxxxx"
dest_desc="Your Website Description"
dest_sqlpass="xxxxxxx"


#######################
# CREATE DOMAIN
#######################

ssh root@"$dest_server" "virtualmin create-domain --domain $site_domain --pass $dest_pass --desc '$dest_desc' --unix --dir --webmin --web --mail --mysql --limits-from-plan --mysql-pass '$dest_sqlpass'"

#######################
# COPY FILES
#######################

ssh root@"$source_server" "rsync -avz -e ssh --progress /home/$source_username/public_html/ root@$dest_server:/home/$dest_username/public_html/"

#######################
# DUMP DB
#######################

ssh root@"$source_server" "mysqldump $source_db > /home/$source_username/$source_db.sql"

#######################
# COPY DB FILES
#######################

ssh root@"$source_server" "scp /home/$source_username/$source_db.sql root@$dest_server:/home/$dest_username/$dest_username.sql"

#######################
# RESTORE DB FILES
#######################

ssh root@"$dest_server" "mysql $dest_db < /home/$dest_username/$dest_username.sql"