Home > Support > HOWTO List > Linux > RSync Secure Backup

Working with Linux howtos

Automated, Secure Backups via Rsync

Want to automate your backups?  Want to do it securely?  Want it to be efficient and fast?  Then Rsync backups over SSH using public/private keys are for you. 

The following script will setup a nightly rsync backup of a directory you specify on your host to another Unix server (whatever you use as remote_host).  The remote host must be running SSHd.

cd /root
# create a private key with no pass phrase.
# You want to make sure no one ever gets access to this file 
# (else they'll be able to log into your remote host)
ssh-keygen -f backup.private.key -t rsa -C "backupkey" -N ""
# pop the public key into a variable
public_key=$(cat backup.private.key.pub)
# add a backup user on the remote machine, install the public key
ssh $remote_host "adduser backupuser;mkdir ~backupuser/backups; mkdir ~backupuser/.ssh;echo
\"$public_key\" > ~backupuser/.ssh/authorized_keys";
# back on the localhost setup a job that will do the backup

echo "
# invoked by /etc/cron.daily/rsyncbackupcronjob
ssh-add /root/.ssh/backup.private.key

# copy a directory to the backup server
rsync --delete --compress --archive --rsh=ssh $directory_to_backup
" > /root/rsyncbackup.sh
chmod +x /root/rsyncbackup.sh

# and then you need a job to lauch the previous one.  This job will execute nightly via cron
echo '#!/bin/bash' > /etc/cron.daily/rsyncbackupcronjob
echo "ssh-agent /root/rsyncbackup.sh" >> /etc/cron.daily/rsyncbackupcronjob
chmod +x /etc/cron.daily/rsyncbackupcronjob

Edit /root/rsyncbackup.sh if you want to change the files/directories you need backed up.