Server Backup Script

Overview

This page presents a script to back up files and a myswl database.

In the example code, we assume that the host storing the backup files is dest.csci.csusb.edu, and the host being backed up is src.csci.csusb.edu.

Configure ssh to run without passwords

Communication between client host and backup system is done over ssh. To make backing up a single command without a password, we use public/private key based authentication rather than username/password.

In the machine to be backed up, run the following as a non-root user to generate a key pair. (Do not set a passphrase.)

ssh-keygen -t dsa -f ~/.ssh/keypair -P ''

Copy the public key to the machine that will store backups.

scp /home/turner/.ssh/keypair.pub dest.csci.csusb.edu:~

On the machine to store backups, append the public key to the ssh list of authorized keys.

cat keypair.pub >> ~/.ssh/authorized_keys2 
chmod 0600 ~/.ssh/authorized_keys2

Connect to the backup machine by running the following from the machine to be backed up.

ssh -i ~/.ssh/keypair web.csci.csusb.edu

There are 2 reasons for doing the previous step. First, you can test that the public key has been correctly generated and installed in the backup machine. Second, it allows you to manually accept the fingerprint of the remote machine into ~/.ssh/known_hosts on the source machine, so that subsequent executions of the script do not require this input, which is necessary if you run the script from a cron job.

Create backup script

Assume that the server src contains several MySQL databases and a directory of static html files that need to be backed up. Also assume that the database password of the root account is root.

Create file backup.sh with the following contents.

# Remove old database dumps.
rm -rf /tmp/bk
mkdir /tmp/bk

# Dump databases.
mysqldump -u root -proot web_programming > /tmp/web_programming.sql
mysqldump -u root -proot gamedev > /tmp/gamedev.sql

# Remove the previous backup archive.
if [ -e /tmp/src.tar.gz ]
then
   rm /tmp/src.tar.gz
fi

# Create backup archive.
tar -czvf  \
    /tmp/src.tar.gz \
    /tmp/bk \
    /var/www/wikis \
    /root/backup.sh \
    /var/www/html

# Copy backup archive to backup server.
scp -i /home/turner/.ssh/keypair \
    /tmp/wiki.tar.gz \
    turner@dest.csci.csusb.edu:/home/turner/bk/


Restoration from backup

To restore a mysql database from a dump, do something like the following. (Use --hex-blob if you are storing binary data in one or more tables.)

mysql -u root -proot --hex-blob -D my_database < my_dump.sql