Using Cron to automate a Rsync backup job
The rsync tool in Linux is very useful for backing up files from one machine to another, and coupled with the Cron scheduling tool it can be used to make a simple yet efficient automated backup. This post outlines how.
Authenticating with the remote system
It is necessary to save your credentials on the remote system, if you don’t then every time rsync is run it will prompt for your password. This is fine when you’re sat at the console, but if the script is running in the background at 3 in the morning it will just get stuck. We’ll get this bit out of the way first.
First create an authorized key file as follows, logged into the source machine as root.
1cd ~ 2ssh-keygen -t dsa 3cd .ssh 4cp id_dsa.pub authorized_keys
Then copy this new file to the target host.
1scp authorized_keys email@example.com:~/.ssh
The next step is to setup the rsync command to copy the data to the remote system. The following command, replacing the paths as appropriate, will do this.
1rsync -avz --del --super /pathto/sourcelocation/ remotehost.domain.com:/pathto/backuplocation/
Next, put the rsync command into a script file so it can be run again. Edit a new text file in your favourite editor, for example /root/backupscript and put the above rsync line into it. Next, make this script executable.
1chmod +x /root/backupscript
Scheduling with cron
Finally the cron scheduler can be configured to run the script at given times. To do this we first create a text file with the details of the script and when we want it to run, copy and paste the following text into a new file
1# (Use to post in the top of your crontab) 2# ------------- minute (0 - 59) 3# | ----------- hour (0 - 23) 4# | | --------- day of month (1 - 31) 5# | | | ------- month (1 - 12) 6# | | | | ----- day of week (0 - 6) (Sunday=0) 7# | | | | | 8# * * * * * command to be executed 9 30 4 * * * /root/backupscript
This configuration will execute the
/root/backupscript file on the 30th minute of the 4th hour every day, every month, every day of the week, i.e. daily at 04:30. To finish off load this configuration in using
1crontab /root/crontab.txt 2crontab -l
Now all you need to do is sit back and wait for 0430 to roll by and then see if it has worked.