Skip to content

Automatic Backup Scripts

This assumes that you have 2 Linux machines / servers – one to backup to the other.

To enable the script to automatically login to the destination server you will need to enabled ssh key based logins.

First off, create an SSH Key on the server.

ssh-keygen -t dsa

Hit enter for all questions.

Run the following command to send the key to the backups server (you will need to enter the password manually)
cat ~/.ssh/id_dsa.pub | ssh backups@backup_server.net "cat - >> .ssh/authorized_keys"

Save the script below into /root/backup.sh and set it executeable (chmod +x backup.sh)


#!/bin/bash
#
# Backup Script
#
# Tim Igoe 2007
#
# Usage - ./backup.sh
#

NOW=`date +”%d-%m-%Y”`

HOST=`echo $HOSTNAME`

DB=”$HOST.$NOW.sql”
FILES=”$HOST.$NOW.website.tar”
EMAIL=”$HOST.$NOW.email.tar”
WWWROOT=”/var/www/”
EMAILROOT=”/home/virmail/”

GZIP=`which gzip`
SCP=`which scp`
RM=`which rm`

mysqldump -u backup –password=secure_password –all-databases > $DB

tar -cpf $EMAIL $EMAILROOT
tar -cpf $FILES $WWWROOT

# Zip it all up
$GZIP $DB
$GZIP $FILES
$GZIP $EMAIL

# Transfer it to backup server
$SCP $DB.gz backups@backup_server.net:~/backups/$DB.gz
$SCP $FILES.gz backups@backup_server.net:~/backups/$FILES.gz
$SCP $EMAILS.gz backups@backup_server.net:~/backups/$EMAILS.gz

$RM $DB.gz
$RM $FILES.gz
$RM $EMAIL.gz

Then finally, set a cron to run nightly / weekly / monthly

crontab -e


# Weekly Server Backup
0 5 * * 6 cd /root/; ./backup.sh

Published inServers

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.