Losing valuable files and data is a frustrating experience many of us have faced. While we understand the importance of backing up our files and data, not everyone has implemented an effective backup solution.

A major cause of data loss is the failure of a local storage system. Good backup strategies involve creating regular, automatic backups and storing at least one copy at a remote location.

A popular method to back up a Linux server or desktop is to use rsync for transferring files to a remote SSH server, and cron for automating the backup process.

Steps to set up automatic remote backup with SSH and rsync:

  1. Set up a passwordless SSH login from your local machine to the remote backup server.
  2. Create a directory on the remote server to serve as a backup target.
    remoteuser@remoteserver:$ mkdir -p ~/backup_folder/folder_01
  3. Ensure the connecting SSH user has full access to the directory on the remote backup server.
    remoteuser@remoteserver:$ chmod -R 777 ~/backup_folder/folder_01
  4. Run your backup script manually on your local machine to test the success of the backup operation.
    localuser@localhost:$ rsync -av --delete /path/to/folder_01/ remoteuser@remoteserver:backup_folder/folder_01

    Sample of a more complete script for automated backup.

    backup.sh
    #!/bin/bash
     
    TARGET="remoteuser@remoteserver:~/backup_folder"
     
    for i in folder_01 folder_02 folder_03; do
    	rsync -av --delete $i/ $TARGET/$i;
    done
  5. Verify on the remote server that the files have been successfully backed up.
    remoteuser@remoteserver:$ ls -l ~/backup_folder/folder_01
  6. Open the crontab editor on your local machine.
    localuser@localhost:$ crontab -e
  7. Configure cron on your local machine to automatically execute your backup script at a specified.
    # Run backup command every day on midnight, sending the logs to a file.
    0 0 * * * rsync -av --delete /path/to/folder_01/ remoteuser@remoteserver:backup_folder/folder_01 >>~/.backup.log 2>&1 
  8. Save and exit the crontab editor.
Discuss the article:

Comment anonymously. Login not required.