Streamline Your Backup Process with Cron and Rsync

Automating Backups with Rsync and Cron in Linux

In this article, we will explore how to use the rsync tool in Linux to automate backups of your files from one machine to another, and how to schedule these backups using the Cron scheduling tool. We will also cover how to save your credentials on the remote system to avoid prompting for your password every time the script runs.

First, let’s create an authorized key file on the source machine as root:

“`

sudo -i -t /root/backupscript

“`

This will log us in as the root user and open the text editor with the backup script file.

Next, copy the authorized key file to the target host:

“`

scp /root/backupscript /root/target_host:/home/user/.ssh/authorized_keys

“`

Now, let’s set up the rsync command to copy the data to the remote system. The following command, replacing the paths as appropriate, will do this:

“`bash

rsync -avz –delete /path/to/source /path/to/target/

“`

This command will copy all files from the source path to the target path, preserving permissions and ownership, and deleting any files that no longer exist in the source directory.

Next, put the rsync command into a script file so it can be run again:

Open a text editor and create a new file /root/backupscript with the following content:

“`bash

#!/bin/bash

rsync -avz –delete /path/to/source /path/to/target/

“`

Make this script executable:

“`bash

chmod +x /root/backupscript

“`

Finally, configure the cron scheduler 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 /root/crontab.txt:

“`text

5 4 * * * /root/backupscript

“`

This configuration will execute the /root/backupscript 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:

“`bash

crontab -l /root/crontab.txt

“`

Now all you need to do is sit back and wait for 0430 to roll by and then see if it has worked. If you want to check the status of the backup, you can use the following command:

“`bash

rsync -avz –delete /path/to/source /path/to/target/

“`

This will run the rsync command and display the status of the backup.

That’s it! With these steps, you have automated backups of your files from one machine to another using rsync and Cron in Linux. By saving your credentials on the remote system, you avoid prompting for your password every time the script runs. Now all you need to do is sit back and wait for 0430 to roll by and then see if it has worked.

Copyright © IT SHOULD JUST WORK. All Rights Reserved.