Skip to content

Instantly share code, notes, and snippets.

@mgeeky
Created December 15, 2019 17:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mgeeky/25084485992ce14377ded8d2f63e44a3 to your computer and use it in GitHub Desktop.
Save mgeeky/25084485992ce14377ded8d2f63e44a3 to your computer and use it in GitHub Desktop.
Simple linux server backup script automating use of rsync and 7zip to create a rotated N backup archives.
#!/bin/bash
#
# Simple utility to perform rotated compressed backups.
# Works best when added to crontab:
# 0 21 * * 1 /root/server-backup.sh
#
# Requirements:
# $ sudo apt-get install p7zip-full rsync
#
# =============================
# CONFIGURATION
# Number of backups to take/rotate
BACKUPS=5
# User to authenticate into server
USER=john.doe
# Server's address/hostname
SERVER=example.com
# Destination path where to backup specified server.
DEST_PATH=<dest-backups-path>
# =============================
if [ -z "$DEST_PATH" ]; then
echo "[!] You must set DEST_PATH correctly."
exit 1
fi
if [ -z "$SERVER" ]; then
echo "[!] You must set SERVER correctly."
exit 1
fi
if [ -z "$USER" ]; then
echo "[!] You must set USER correctly."
exit 1
fi
info_file=$DEST_PATH/last-backup.txt
out=`ssh $USER@$SERVER whoami 2>/dev/null`
if [ "$out" != "$USER" ]; then
echo "[!] Could not SSH into target server!"
exit 1
fi
backup_num=0
last_backup=
now=`date '+%Y-%m-%d_%H-%M-%S'`
if [ ! -x last-backup.txt ]; then
touch $info_file
echo "[?] Initiating first backup."
else
backup_num=`sed -n '1p' $info_file`
last_backup=`sed -n '2p' $info_file`
echo "[?] Last backup (no. $backup_num) took place on: $last_backup"
fi
echo "[+] Backing up. This will take a longer while..."
backup_dir=$DEST_PATH/$((backup_num % BACKUPS))
if [ ! -x $backup_dir ]; then
mkdir -p $backup_dir
fi
from=$USER@$SERVER:/
echo -e "\tBackup source dir: $from"
echo -e "\tBackup destination dir: $backup_dir"
rsync -aAXz --rsync-path="sudo rsync" --info=progress2 --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} $from $backup_dir
echo "[+] Finished syncing. Compressing..."
output_file="backup-$backup_num-$SERVER-$now.7z"
7z a $output_file "$backup_dir/*"
rm -rf $backup_dir
echo "[+] Backup stored at: $output_file"
backup_num=$((backup_num+1))
echo $backup_num > $info_file
echo $now >> $info_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment