Automated backups with 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.

remote_host=ahostname.com
directory_to_backup=/a/directory/to/backup

{
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 "
#!/bin/bash
# invoked by /etc/cron.daily/rsyncbackupcronjob.sh
ssh-add /root/backup.private.key

# copy a directory to the backup server
rsync --delete --compress --archive --rsh=ssh $directory_to_backup backupuser@$remote_host:backups/
" > /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.sh
echo "ssh-agent /root/rsyncbackup.sh" >> /etc/cron.daily/rsyncbackupcronjob.sh
chmod +x /etc/cron.daily/rsyncbackupcronjob.sh
}

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

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading ... Loading ...

Related Articles

Random Articles

Post a Comment