code

Remote Server Backups to a Mac Using Rsync and Crontab

If you’re using a mac you might have come across a lot of different methods and commands to backup a remote server to your local mac. You can do this for nightly backups and what’s great is that you can also have your Time Machine drive backup your backups.

I have setup a 14-day incremental backup to a remote server. You’ll need need to save the following code as backup.sh and execute it nightly using crontab. You’ll also need to give the file execute permissions and run it as the root user so the permissions match up. You’ll need to setup crontab to run with the root account, not your own user account.

Shell Script

#!/bin/bash

#Website Backup Script

#Backup Container Folder
BACKUPFOLDER="/Volumes/Huge\ Space/Server\ Backups/VPS/"

#Todays date in ISO-8601 format:
DAY0=$(date +"%Y-%m-%d")

#Yesterdays date in ISO-8601 format:
DAY1=$(date -v "-1d" +"%Y-%m-%d")

#The source directory:
SRC="'ssh' remotebackupuser@mydomain.com:/"

#The target directory:
TRG="${BACKUPFOLDER}${DAY0}"

#The link destination directory:
LNK="${BACKUPFOLDER}${DAY1}"

#The rsync options:
OPT="-azHP --rsync-path='sudo rsync' -e"
MOREOPT="--delete --link-dest=$LNK --exclude=/proc --exclude=/sys --exclude=/dev --exclude=/tmp"

#Execute the backup
eval caffeinate rsync $OPT $SRC $TRG $MOREOPT

#14 days ago in ISO-8601 format
DAY14=$(date -v "-14d" +"%Y-%m-%d")

#don't escape spaces for expired dir
EXPIREDDIR="/Volumes/Huge Space/Server Backups/VPS/${DAY14}" 

#Delete the backup from 14 days ago, if it exists
if  [ -d "$EXPIREDDIR" ]
then
rm -Rf "$EXPIREDDIR"
fi

crontab

You’ll need to make sure your mac is awake everyday at the same time. This is is easy to do in System Preferences. Click Energy Saver and then the Schedule button.

crontab Command

12:02am everyday

2 0 * * * cd '/Users/ME/Shell Scripts' && ./backup.sh

GZIP & Difficult Files

If some files still aren’t backing up properly or you are having issues restoring them because of permissions on your own backup machine, consider creating archives of files using backup tools on the server and then backing up the folder where the archives live. For example, backing up SSL certificates will cause some issues with permissions. Check out Webmin Backup if you are using Linux-based machines.

I care about what you have to say. Comment now...