August 23, 2011

Simple Server Backup To FTP Using TAR

vi /root/backup.sh
#!/bin/sh

# prostoorgru.blogspot.com

### MySQL Connection Params ###
MYSQLU="root"
MYSQLP="hackme"
MYSQLS="localhost"

### FTP Connection params ###
FTPD="/backup/server3"
FTPU="ftp_user"
FTPP="ftp_password"
FTPS="ftp_server"

### Binaries ###
TAR="$(which tar)"
FTP="$(which ftp)"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

## Time format YYYY-MM-DD_HH-II-SS ###
NOW=$(date +%Y-%m-%d_%H-%M-%S)


### Temporary backup directory ###
TMP_BACKUP_DIR=/tmp/backup$NOW
mkdir $TMP_BACKUP_DIR

### Backup itself ###
# Examples #
cd /etc && $TAR -czpf $TMP_BACKUP_DIR/my-etc-configs.tgz *
cd /home/example.com && $TAR -czpf $TMP_BACKUP_DIR/example.com.tgz --exclude=*.log --exclude=*.zip *
cd /root && $TAR -czpf $TMP_BACKUP_DIR/my-shell-scripts-from-root.tgz *.sh

### MySQL ###
DATABASES="$($MYSQL -u$MYSQLU -h $MYSQLS -p$MYSQLP -Bse 'show databases;')"
for db in $DATABASES
  do
    FILE=$TMP_BACKUP_DIR/$db.sql.gz
    $MYSQLDUMP --add-drop-table --allow-keywords -q -c -u $MYSQLU -h $MYSQLS -p$MYSQLP $db $i | $GZIP -9 > $FILE
done


### Now collect everything into one archive ###
ARCHIVE=`hostname`_$NOW.tgz
cd $TMP_BACKUP_DIR && $TAR -czf $TMP_BACKUP_DIR/$ARCHIVE --exclude=$ARCHIVE *

### Upload to FTP ###
cd $TMP_BACKUP_DIR
$FTP -n $FTPS <<END_SCRIPT
quote USER $FTPU
quote PASS $FTPP
cd $FTPD
mput $ARCHIVE
quit
END_SCRIPT

### Clean ###
rm -rf $TMP_BACKUP_DIR

echo ""
Explanation of commands in "Backup itself" section:
cd %folder_to_back-up% && tar to tmp_dir/%archive_name%.tgz --exclude=%something% *pack_everything*
The last * symbol stands for 'archive everything'. If you need to back up only specific file type, pass the *.ext pattern, e.g. *.php.

This will add an entry to the crontab file telling your system to execute a backup task every 12 hours -- at 1AM and 1PM (i.e. 13:00) at top of the hour (i.e. 00 minutes):
chmod +x /root/backup.sh && echo "00 1,13 * * * sh /root/backup.sh 2>/dev/null" >> /etc/crontab
You can generate any cron schedule that specifically fits your needs.

Sources:

No comments: