HostOnNet Blog


Remote Backup Linux Server With Rsync

rsync

To Remote backup linux server with rsync, create a bash script.

mkdir /usr/hostonnet/

Create file

vi /usr/hostonnet/backup_remote.sh

Add following content

#/bin/bash
#title           : backup_remote.sh
#description     : Backup to remote server with rsync
#web             : http://blog.hostonnet.com/remote-backup-linux-server-with-rsync

REMOTE_BACKUP_LOCATION="root@BACKUP-SERVER-IP:/BACKUP-PARTITION/`hostname`/"

date +"%d-%b-%Y %T" > /home/backup_remote_time.txt

/usr/bin/rsync -avz --delete --exclude={/boot,/dev,/proc,/sys,/tmp,/run,/mnt,/media,/lost+found,/backup} "-e ssh -p 22" / $REMOTE_BACKUP_LOCATION

# Uncomment if you need email notification after cron run
# echo "Backup taken to $REMOTE_BACKUP_LOCATION" | /bin/mail -s "Backup finished on `hostname`" YOU@YOUR-DOMAIN.COM

In above code, replace following

BACKUP-SERVER-IP = IP of remote backup server
BACKUP-PARTITION = Partition (mount point) on which you need backup stored, for example "backup".
YOU@YOUR-DOMAIN.COM = Replace with your email address, so you get email after remote backup is done.

Make script executable

chmod 755  /usr/hostonnet/backup_remote.sh

We need to set cronjob to run the backup script.

crontab -e

Add

@weekly /usr/hostonnet/backup_remote.sh >/dev/null 2>&1

This will run backup script every week.

It is good practice, you made sure cronjob runs on your server, to check crond deamon is running, run

service crond status

If you don’t have crond running, refer

http://blog.hostonnet.com/centos-crontab-command-not-found

Running Backup Manually

Run the command manually to see what will happen when it run via cron

/usr/hostonnet/backup_remote.sh

First time, it ask us to accept SSH key, so type “yes”, you must manually do this or cron will fail.

Once you type yes, it will ask for password. Again, cron can’t type password for you. So we have to setup password less authentication with SSH Key.

Setup Password-less Authentication

Check if you have a public Key.

ls -l /root/.ssh/id_rsa.pub 

If you don’t have a public key, generate one with following command.

ssh-keygen -t rsa -N '' -b 2048

You need to copy content of your public key to the server on which you need to login with out password. In our cause, it is the backup server.

cat /root/.ssh/id_rsa.pub 

Copy the content of the file.

Login to Backup server, edit authorized_keys

vi /root/.ssh/authorized_keys

Add public key, save and exit.

Run the backup command again, it will not ask for password

/usr/hostonnet/backup_remote.sh

Now everything is set, when cronjob is run, backup will be taken.


Posted in Linux