I have always been an advocate for using a control panel when dealing with multi site hosting.  In my case I use VestaCP, which is a great, simple, free alternative to the big boys like Plesk and cPanel.  The only issue though, is space for backups.  On the server I normally have 3 to 5 days backed up, which is great, however if you find out your site had been hacked 7 days ago, all your backups on the server are tainted.  This happened to me a few years back, and one of my sites was hacked for almost a month before I found out.

It was because of this I created a simply python script to make offsite backups.  I am lucky enough to have myself a desktop NAS (Network Area Storage) in my home office with 10TB of space, more then enough for storing more than 3-5 days of backups.  As I rely on this I figured maybe others could use this script as well.

 

Prerequisites not covered in this post:

  • Dynamic DNS for home network access (will be covered in another post to come)

Preparing for backups:

Before we get to the script, you will need to make sure that your VestaCP server can authenticate with the remote backup server for passwordless authentications, after all this is an automated script, so you need to be able to transfer data without having to manually enter a password.  To do this we need to generate an RSA key pair on the VestaCP server, AND transfer the public key to the offsite backup server.

To do this, as ROOT you can use the following command:

This will generate an RSA keypair with 4096 bit encryption and a comment relative to what the key is used for.  At the prompts you will have some choices to make, including the name of key pair (if you do not have any others, you can use the default id_rsa), if you wish to have a password (select no, as you need this to be fully automated).

Now that we have our key generated, we need to get the public key onto the offsite backup server:

Note: although the on the server you need to run these commands as ROOT due to permissions on the backup folders and commands used in the next section, the user you upload this too does not need to be a root account.  The user and host used in the above command will also be used in the following script as sshUser and sshHost

The Code:

Create a file called backup-to-nas.py in a folder like /opt/scripts

call it via the crontab (as root type “crontab -e“)

Then every day at 6am, it will take all your site backups and move it to your offline backup server.