Simple rsync backup of your remote server w/ crontab

If you have a remote server, e.g. for you website, small business or whatever, it is a good idea to replicate it regularly onto local storage. You at least want /etc, /home, /var/www, /usr/local to be in the backup. Maybe more stuff, depending on what you are doing.

For now I assume you are running the backup on OS X’s user with admin/sudo rights, or some Linux user with sudo rights.

The reason why we want to do this with sudo and root on the remote system is to have a simple way to backup the whole system with all files, users and permissions. If you only want to backup a remote user, you don’t need the whole sudo and root part, but can use the remote user login instead.

First, you need the backup script:


if [ "${UID}" != 0 ]
    echo "Must be run as root."
    exit 1

shopt -s nocasematch

pushd `dirname $0` > /dev/null
popd > /dev/null

if [[ "${PWD}" != "${SCRIPTPATH}" ]]
    echo "Wrong path: ${PWD}"
    exit 2

RSYNC_RSH="ssh -C -o IdentitiesOnly=yes -i /Path/to/key/without/password"
RSYNC_CMD='rsync -aP --delete --delete-after'

($RSYNC_CMD -e "${RSYNC_RSH}" root@${RSYNC_HOSTNAME}:/etc :/home :/root :/usr/local :/var/www . > /tmp/rsync.log 2>&1 ) || \
(>&2 echo "An error occured while doing the backup: " ; cat /tmp/rsync.log )

exit $?

Adjust your hostname accordingly and also the directories to be backed up. Use the :/dir notation to reuse the SSH connection. Also make sure to use SSH key authentication, so no password is needed, since this backup is supposed to run via crontab. SSH access as root must only be allowed via key exchange! Make sure to disable password access, or else you are running a security risk! Also, keep the SSH key secret — it is the door to your server!

There are probably more secure ways, but they are more complicated than this.

Next up, put you script somewhere your sudo user can run it, and edit the crontab via “crontab -e”:

MAILTO=user@domain  # or simply your local user, to put it into the local mbox
0 * * * *       cd /Users/youruser/Documents/Backup && sudo /Users/youruser/Documents/Backup/

You can make the script runnable with sudo without password by adding the following line to your /etc/sudoers file:

# allow passwordless access to the backup script
youruser ALL = (ALL) NOPASSWD: /Users/youruser/Documents/Backup/

The script will only generate output on an error, hence cron will only send an email if there is an error.

If you are now also running TimeMachine, your server will have a nice, hourly history of backups.