Wednesday 4 May, 2011

Automated DB backup script on Fedora

Here is Script to do automated Mysql and postgress backup.
You need to create .pgpass file is users home diretory.

.pgpass file format is as follows


host:postgress_port:dbname:pg_db_username:pg_db_password


And password less login to remote backup host.

Here is the script





#!/bin/bash
#
# Mysql and Postgres database backup script
#
# Pre-Backup script
# - Stops Service
# - Takes a MySQL and Postgres Dump
# - Start the service

# Which service to mess with
SERVICE="httpd"

# MySQL Properties
DBDUMPDIR="/opt/dbdump"
DBNAME="db"
DBHOST="localhost"
DBUSER="dbuser"
DBPASSWORD="dbpass"

echo "Shutting down Service..."
/etc/init.d/${SERVICE} stop

while ps ax | grep -v grep | grep ${SERVICE} > /dev/null;
do
  echo "...stopping..."
  sleep 5
done

echo "Creating MySQL Dump..."
if [ ! -d "${DBDUMPDIR}" ]; then
  mkdir -p ${DBDUMPDIR}
fi
#mysqldump --host=${DBHOST} --user=${DBUSER} --password=${DBPASSWORD} ${DBNAME} > ${DBDUMPDIR}/${DBNAME}_`date +%d-%m-%y-%T`.sql
sleep 5
echo "Creating Postgres Dump..."
pg_dump pg_db -U pg_user -f /opt/dbdump/pg_db_`date +%d-%m-%y-%T`.sql
sleep 10
echo "Restarting Service..."
/etc/init.d/${SERVICE} start

while ! ps ax | grep -v grep | grep ${SERVICE} > /dev/null;
do
  echo "...starting..."
  sleep 5
done
echo "Uploading files to Remote Backup Server...."
rsync -av -e "ssh -p 22456" /opt/dbdump/* sshuser@backuphost.domain.com:/home/sshuser/db_backup
exit 0

Now create a crontab.

35 12 * * * /usr/local/etc/db_backup.sh >> /var/log/db_backup.log
 
                                                                                     1,1           Top

No comments: