Aprium Software

Mysql Remote Backup

This article covers how to write a Mysql backup script for shell. First of all we need to create the file so open a new text file called backup.sh and set the first line as.

#!/usr/bin/expect

We are using an expect script because it is better suited to dealing with remote requests and responses. The script is going to run like a command and will use the following parameters.

set server [lindex $argv 0]
set password [lindex $argv 1]
set database [lindex $argv 2]
set filename [lindex $argv 3]

The next step is to ssh login onto your web-server by using the following code. The normal user@domain for the ssh will be passed in through the $server variable when the script runs.

## Login to the server
spawn ssh $server
expect "yes/no" { send "yes\r" }
expect "password:" { send "$password\r" }
expect "# "

## Change to backup dir
send "cd /backupr\r"
expect "# "

The script is ready for the database backup, i have added a couple of options to this but you will probable want to customize this.

## Create backup
send "mysqldump --add-drop-database --add-drop-table --opt -u root $database > $filename \r"
expect "# "
send "exit\r"
expect "closed"

This part will now copy the database backup back to your local machine.

## Copy the backup file to local
set timeout -1
spawn scp "username@www.aprium.net:/home/httpd/dbbackup/$filename" /Users/colin/Backup
expect "password:" { send "$password\r" }
expect "# "

Save the script and you can now use the script by running.

./backup.sh "user@domain" "password" "aprium" "backupname"

Hire

If you need a London based Drupal developer you can hire me. Check the availability page and contact me on info@aprium.net.

 

Powered by Drupal, an open source content management system

Copyright Aprium 2010