Automate your Linux server backups

Posted on Sat, 25 July 2015 in development

We all know pretty well that backups are necessity. I would like to share a simple and effective way to automate the backing up of your Linux server to Dropbox. Without further ado, let’s get started.

Prerequisites

  1. Linux server to backup (CentOS 7 in my case). 1.1. Root access 1.2. Ability to run shell scripts and cron jobs.
  2. A Dropbox account.

Integrate with Dropbox

This is actually pretty ease one. Just follow the instructions on Dropbox Uploader‘s GitHub page. I use App permission option for access level.

After completing the autentication and authorization process, let’s continue.

Script the backup process

Create a new shell script to store the commands. I use vi editor on my CentOS box.

# create new file
touch /var/mysh/server-backup.sh

# open for edit
vi /var/mysh/server-backup.sh

The content is as follows (with few omits regarding the actual payload):

# server-backup.sh
# This is a backup script
# - tar listed files and directories
# - gzip the tar package
# - upload to Dropbox
# - clean up.
# Jani Karhunen 2015-07-24

# create target filename for package
# E.g. 2015-07-25_150112-box1-backup.tar.gz
NOW=$(date +"%Y-%m-%d_%H%M%S")
echo timestamp = $NOW
save_path='/var/backup'
save_file_base=$save_path/$NOW-box1-backup
save_file=$save_file_base.tar

echo backup to $save_file
# Paths to backup
path[0]='/etc/sysconfig/iptables'
path[1]='/etc/ssl'
path[2]='/var/www'
path[3]='/var/mysh'
path[4]='/var/log'

# Zip it
for t in "${path[@]}"
do
    tar rfv $save_file $t/
    echo $t saved!
done

gzip $save_file
echo zipped $save_file

echo upload $save_file.gz to Dropbox
/var/mysh/dropbox_uploader.sh -f /root/.dropbox_uploader upload $save_file.gz $NOW-box1-backup.tar.gz

echo clean up
rm -f $save_file.gz

echo All done.

Save and edit vi. Note: I do not have any MySQL / MariaDB databases to backup at the moment on this server. If you do, mysqldump will be your friend.

Add execution rights for the script (just for the user aka root)

chmod u+x /var/mysh/server-backup.sh

Test run the script that everything is in order before automating the process.

sh /var/mysh/server-backup.sh

If everything went well, as it did, since we are professionals here, time to proceed to the last step.

Automate with cron

Now that we have a working script in our hands, the final step is to automate the backup process with cron. Add new cron job as root with

crontab -e

Add the following job (logs SDTOUT and STDERR to a log file)

# Run backup script every night at 02:10
10 2 * * * /var/mysh/server-backup.sh >> /var/log/server-backup.log 2>&1

Hey presto! Now you and I have a fully automated and cloud powered backup scheme running.

Credits: This article of mine is inspired by Matthias Reining’s blog post, with few adaptations to fit my purpose. Big thanks to Andrea Fabrizi for making it easy to use Dropbox from shell scripts.