Automate backup with rsync over ssh and crond
rsync over ssh provides an excellent way to automate your backups
Here I show you how a backup of my cvs-repository is daily updated on another machine. You can of course backup any directory this way.
We have two machines, one with the data and one where we want to put the backup of the data on. Below we follow the following aliasses for these machines:
- <localhost> : the machine that has the data
- <remotehost> : the machine we want to put the backup on
Replace these with your own machine-names or ip-numbers.
Automate ssh login
Generate key pair
Create a keypair on <localhost>. Login in this machine as the user you want to do the backup:
ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/matto/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/matto/.ssh/id_rsa. Your public key has been saved in /home/matto/.ssh/id_rsa.pub.
Copy public key to remotehost
cd .ssh scp id_rsa.pub <remotehost>:.ssh/<localhost>_rsa.pub
Replace these with your own machine-names or ip-numbers. <remotehost> is the name or ip-number of your remotehost you want to login to. So if your localhost is known as gandalf remote host as frodo then the command is:
scp id_rsa.pub gandalf:.ssh/frodo_rsa.pub
Import the public key in the autorized_keys file
Login to <remotehost>
cd .ssh cat <localhost>_rsa.pub >> authorized_keys
After this you should be able to make a ssh connecton from <localhost> to <remotehost> without being required to give a password.
By renaming id_rsa.pub to <localhost>_rsa.pub it is easier to manage multiple keys.
Backup the data with rsync
First we try a rsync run. If everything goes well, we will scedule and perform updates with the help of crond in the next step.
/usr/bin/rsync -avz -e ssh /var/cvsroot/ <remotehost>:/var/backup/cvsroot/This command copies the content of /var/cvsroot/ to the directory /var/backup/cvsroot/ on <remotehost>. You can of course use different paths. Take care of the usage of the trailing /, rsync is picky about this.
Create a crontab entry
Use crond to automate the backup process for you.
Edit the contrab file with the command crontab -e. Add a line:
8 3 * * * /usr/bin/rsync -avz -e ssh /var/cvsroot/ <remotehost>:/var/backup/cvsroot/At 8 minutes past 3 crond will perform the rsync process for you.
Tune the rsync command to your needs
When a file on <localhost> is removed (deleted) it will not automaticly be deleted on <remotehost>. This behaviour of rsync depends on the command you have given.
If you want deleted files also to be deleted on your rsynced backup, then add the switch "--delete" to the rsync command.
/usr/bin/rsync -avz --delete -e ssh <source> <remotehost>:<destiny>