Two-way remote backup using rsync

After a recent hard drive failure, I decided to revisit the backup strategy I employ in my local network. While you can find a lot of different OSS solutions for this these days, I prefer the simplicity of rsync. In the following, I will describe how to use it to set up file synchronization between two Linux servers. Unless otherwise noted, each of the following commands needs to be executed on both servers.

Start by creating a backup user by running the following command:

server$ sudo useradd -m -g backup rsync-backup
server$ sudo passwd rsync-backup

Create an private key to allow key-based authentication over ssh.

server$ su rsync-backup
server$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/rsync-backup/.ssh/id_rsa):
Created directory '/home/rsync-backup/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/rsync-backup/.ssh/id_rsa.
Your public key has been saved in /home/rsync-backup/.ssh/id_rsa.pub.

Then, copy the ssh key over to the other server.

server$ ssh-copy-id -i .ssh/id_rsa.pub other-server

At this point, you should be able to log into the other server as rsync-backup without having to enter your password.

Next, create the script that will perform the actual backup. In my case, I want to backup my ~/Documents directory to a directory under the rsync-backup user’s home on the other server.

nano /home/rsync-backup/backup
> #!/bin/bash
> SOURCE=/home/user/Documents
> USER=rsync-backup
> HOST=other-server
> TARGET=$USER@$HOST:/home/rsync-backup/this-server
> # use --progress to show at runtime
> rsync -avrz $SOURCE $TARGET

Now, lets set up a cron job for this user to run the backup job once a week.

server$ crontab -u rsync-backup -e

# add the following line
0 4 * * 1 /home/rsync-backup/backup

Finally, lock the backup user account to prevent ssh access without a key.

server$ sudo passwd -l rsync-backup

At this point, both servers will sync the specified directories once a week.

 

Author: Ben

Leave a Reply

Your email address will not be published. Required fields are marked *