Website Backup With rsync

One thing that kept me from getting my blog back up for a while was the lack of a consistent backup strategy for the WordPress content and the website as a whole. Website backup should be easy, with these commands and the following script, it's very easy.

This is just a starting point though, I have some ideas about backup that I plan to explore in future experiments.

Manual Runs

Quick backup command lines:

ssh user@host mysqldump --all-databases -p --result-file=db-backup-`date +%Y%m%d`.sql
rsync -av --delete user@host:/remoteSource localDestination

This creates a mirror image of the remote system directory tree and will delete local files that don't exist remotely. Also, before doing the rsync it creates a dump of the MySQL database (useful for WordPressers) so you have that solidly backed up too, but you do have to punch in the password via the console. It's a bad idea to pass the password directly on the command line, because it could be exposed to other users on a shared system.

Automation

This can be automated using a Bash script + Expect, of course. (and then stuck in a crontab)

#!/bin/bash

USER=someuser
HOST=somehost

REMOTE_DIRECTORY=/home/someuser
LOCAL_DIRECTORY=website 

MYSQL_BACKUP_CMD="ssh $USER@$HOST mysqldump --all-databases -p --result-file=db-backup-`date +%Y%m%d`.sql"
MYSQL_PASSWORD=somepassword

RSYNC_BACKUP_CMD="rsync -av --delete $USER@$HOST:$REMOTE_DIRECTORY $LOCAL_DIRECTORY"

echo "==========================="
echo "Backing up MySQL database."

MYSQL_EXPECT=$(expect -c "
spawn $MYSQL_BACKUP_CMD
expect "password:"
send "$MYSQL_PASSWORDr"
expect eof
")

# Must wait for EOF or you will get 0-length files 
# as expect surreptitiously terminates.

echo "==========================="
echo "$MYSQL_EXPECT"

echo "==========================="
echo "Running rsync."

echo $RSYNC_BACKUP_CMD
$RSYNC_BACKUP_CMD

echo "==========================="
echo "Done."

Expected output from the script

===========================
Backing up MySQL database.
===========================
spawn ssh someuser@somehost mysqldump --all-databases -p --result-file=db-backup-20100926.sql
Enter password: somepassword
===========================
Running rsync.
rsync -av --delete someuser@somehost:/home/someuser website
receiving incremental file list
[...]
sent 33643 bytes  received 7361999 bytes  31946.62 bytes/sec
total size is 3273865012  speedup is 442.67
===========================
Done.