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.
cd ~ ssh-keygen -t dsa cd .ssh cp id_dsa.pub authorized_keys
Then copy this new file to the target host.
scp authorized_keys [email protected]:~/.ssh
The next step is to setup the rsync command to copy the data to the remote system. The following command, replacing the italicised sections as appropriate, will do this.
rsync -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
and put the above rsync line into it. Next, make this script executable.
chmod +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
# (Use to post in the top of your crontab) # ------------- minute (0 - 59) # | ----------- hour (0 - 23) # | | --------- day of month (1 - 31) # | | | ------- month (1 - 12) # | | | | ----- day of week (0 - 6) (Sunday=0) # | | | | | # * * * * * command to be executed 30 4 * * * /root/backupscript
This configuration will execute the
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
crontab /root/crontab.txt crontab -l
Now all you need to do is sit back and wait for 0430 to roll by and then see if it has worked.