Backup Mysql Database on remote FTP Server

Here a simple script to backup all your mysql database on a remote FTP server. The script weekly overwrite the backup so you have full backup of your DBs for the last 6 days and your FTP server doesn't run out of space.

#!/bin/sh
 
BACKUP="/path/to/temp/dir/$$"
 
DAY=$(date +"%a")
 
### MySQL Setup ###
MUSER="root"
MPASS="your_root_password"
MHOST="localhost"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
 
### FTP server Setup ###
FTPUSER="ftp_username"
FTPPASS="ftp_password"
FTPHOST="ftp_host"
 
mkdir -p $BACKUP
 
### Start MySQL Backup ###
# Get all databases name
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 FILE=$BACKUP/$(date +"%a")-$db.gz
 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE
 echo "Saving "$db" to "$FILE
done
 
### Dump backup using FTP ###
echo "Sending file via FTP"
 
ftp -ni $FTPHOST > /tmp/ftp.worked 2> /tmp/ftp.failed <<END_SCRIPT
quote USER $FTPUSER
quote PASS $FTPPASS
lcd $BACKUP
binary
mput *.gz
quit
END_SCRIPT
 
if [ -s /tmp/ftp.failed ] 
then
   echo "Problem while sendig file ... "
   cat /tmp/ftp.failed | mail -s "Problem while backup" yourmail@yourdomain.com
else
   echo "File sent successfully ... "
   echo "Deleting temporary backup direatory"
   echo $BACKUP
   rm -rf $BACKUP
fi

Once you have set the parameters and saved the file edit your cron for a nightly backup and add a line like

# FTP backup
0 2 * * * /path/to/your/file/do_backup.sh > /path/to/your/file/cron.log

Leave a Reply

Yes !