Linux

Linux Auto Backup Files to Synology Device

Since I actually use virtual machines for all of my work, standard backups of the VM files are very important to me. I recently decided to setup a script to auto backup my Virtualbox VM to my Synology drive, so wanted to share my steps in case others had a similar requirement.

I use Ubuntu but most steps should work for all linux distros.

Credentials File

Create a new file in your home directory with the following details. Since the remote directory requires a username and password to connect, we will need to reference this file in a future step. Although its also possible to specify the credentials directly in the fstab file, that will not work if your password contains any special characters. Save the file as ‘.synology_cred’.

username=your_username
password=your_password
domain=WORKGROUP

Auto Mount Setup

#Make sure you have the required packages:
sudo apt install cifs-utils

#Make new directory where synology will be mounted to:
sudo mkdir /media/synology

#Edit fstab file, the config file for mounted drives:
sudo cp /etc/fstab /etc/fstab.bak
sudo vim /etc/fstab

Copy the following line to the end of the fstab file, replacing the placeholders with your information. The ‘vers’, or version, will depend on the samba implementation for the system you are connecting to. 2.0 was implemented for Windows 7, and is what worked for me. You can also try 3.0, created for Windows 10, if 2.0 does not work.

//your_synology_ip_or_hostname/folder_name /media/synology cifs vers=2.0,iocharset=utf8,credentials=/home/your_user/.synology_cred,uid=your_mount_as_user 0 0

Backup Script

Now that the OS can access the drive through a mount location, we can write our script to zip and copy files. For my example below, I will be backing up a Virtualbox VM. I will save this file as ‘mybackupscript.sh’ in my home directory (~/).

#!/bin/bash

#Gzip vm directory:
tar -czvf /new_backup_file_path.tgz /path_to_your_vm_directory

#Move gzip file to some directory in your synology:
rsync /new_backup_file_path.tgz /media/synology/some_backup_folder_in_your_synology

#Remove local backup file after complete:
rm /new_backup_file_path.tgz

Make the backup file executable:

sudo chmod +x my_backup_script.sh

Auto Execution

The last step is to automate execution of our script by setting up a cron job.

Edit your user’s list of scheduled jobs:

crontab -e

At the end of the file, add your schedule entry. You may use this handy utility for setting your schedule if you are not that familiar with crontab rules - https://crontab.guru

For my example, I want to execute every day at 5AM:

00 05 * * * /home/your_user/vm_backup.sh