Backup MySQL db and web directory to FTP server – Shell Script

This shell script will create the backup of a database, archive the mention web directory, archive the backup directory then upload it on ftp server

# MySQL User
USER='sql-user'

# MySQL Password
PASSWORD='your-password'

# Backup Directory - WITH TAILING SLASH IF PATH OTHER THEN '.'!
OUTPUT="/your-backup-path"
hostname='server-name'
FTPHOSTNAME="ftp-server-address"
FTPUSERNAME="ftp-user"
FTPPASSWORD="ftp-password"
LOG_FILE=$OUTPUT/backup_log.log

##### Execute the backup
TIMESTAMP=`date +%Y%m%d_%H%M%S`;
mkdir $OUTPUT/$hostname$TIMESTAMP;
OUTPUTDEST=$OUTPUT/$hostname$TIMESTAMP;

echo "Starting MySQL Backup";
echo `date`;

mysqldump --user=$USER --password=$PASSWORD your-dbname > $OUTPUTDEST/dbname-$TIMESTAMP.sql

gzip $OUTPUTDEST/dbname-$TIMESTAMP.sql

#zip the web directory with exclude recordings
zip -r9 $OUTPUTDEST/SiteName-$TIMESTAMP.zip /var/www/your-website-directory-path -x /var/www/your-website-directory-path/media/recordings/\*

#zip the latest backup directory
zip -r9 $OUTPUTDEST.zip $OUTPUT/$hostname$TIMESTAMP

# move to backup directory
cd $OUTPUT

#Upload file to FTP now
ftp -inv $FTPHOSTNAME << EOF
user $FTPUSERNAME $FTPPASSWORD
binary
hash
cd backup-directory
put $hostname$TIMESTAMP.zip
ls
bye
EOF

#remove zip file
rm -rf $hostname$TIMESTAMP.zip
exit

if test $? = 0
then
    echo "Database Successfully Uploaded to Ftp Server
        File Name $OUTPUTDEST/dbname-$TIMESTAMP.sql.gz " > $LOG_FILE
else
    echo "Error in database Upload to Ftp Server" > $LOG_FILE
fi

Leave a Reply

Your email address will not be published. Required fields are marked *