上回贴出了用rsync进行两机备份的shell脚本一文,那个脚本当中有BUG,现在做一个更新,测试完全可用,贴出来,看了旧版脚本的朋友别忘了更新一下,脚本如下:

#!/bin/bash
# This script is used to do backup and rsync works for servers. Please finish the config part first before use it.
# ./backup.sh (db_rsync|www_rsync)
# By Chen Zhidong
# http://sillydong.com

#########config begin####################

BINPATH="/usr/bin"
LOGPATH="/home/backlogs"

DB_DUMP="/home/database/"
LOCAL_WWW="/home/www/"

DB_USER="xxx"
DB_PASS="xxxx"
DB_HOST="127.0.0.1"

PASSFILE="/xxx/xxxxx"
RSYNC_NAME="xxxxxx"
RSYNC_IP="xxx.xxx.xxx.xxx"

#pay attention to the sed part of this sentence, check it before using!
IP=`ifconfig | grep "venet0:0" --after-context=1 | sed -n 's/..*addr:\(..*\)  P-t-P..*/\1/p' | sed '/127.0.0.1/d'`

#########config end######################

db_dump(){
  DBS=`$BINPATH/mysql --user=$DB_USER --host=$DB_HOST --password=$DB_PASS -Bse 'show databases'`
  for db in $DBS
  do
    case $db in
      "information_schema")
      ;;
      "mysql")
      ;;
      "test")
      ;;
      *)
        echo "Dump $db begin at $(date)" >> $LOGPATH/db_dump.log
        $BINPATH/mysqldump --opt $db --user=$DB_USER --host=$DB_HOST --password=$DB_PASS  > $DB_DUMP/$db-$(date +%F).sql
        echo "Dump $db done at $(date)" >> $LOGPATH/db_dump.log
      ;;
    esac
  done
}

db_rsync(){
  echo "Doing db_rsync..."
  echo "db_rsync begin at $(date)!" >> $LOGPATH/db_rsync.log
  rsync -rvlHpogDtS --delete --password-file=$PASSFILE $DB_DUMP --exclude *\log\* --exclude *\backup\* --exclude *.rar --exclude *.zip --exclude *mysql* --exclude *.err* --exclude *.pid* --exclude *\test\* rsync://$RSYNC_NAME@$RSYNC_IP/${IP}_db_lio >> $LOGPATH/db_rsync.log
  echo "db_rsync done at $(date)!" >> $LOGPATH/db_rsync.log
}

www_rsync(){
  echo "Doing www_rsync..."
  echo "www_rsync begin at $(date)!" >> $LOGPATH/www_rsync.log
  rsync -rvlHpogDtS --delete --password-file=$PASSFILE $LOCAL_WWW --exclude *\log\* --exclude *\backup\* --exclude *.rar --exclude *.zip rsync://$RSYNC_NAME@$RSYNC_IP/${IP}_www_lio >> $LOGPATH/www_rsync.log
  echo "www_rsync done at $(date)!" >> $LOGPATH/www_rsync.log
}

#Script begin here

if [ ! -d $LOGPATH ];then
  mkdir $LOGPATH
fi

case $1 in
  db_rsync)
    db_dump 2>> $LOGPATH/rsync_error.log
    db_rsync 2>> $LOGPATH/rsync_error.log
  ;;
  www_rsync)
    www_rsync 2>> $LOGPATH/rsync_error.log
  ;;
  *)
    echo "$(date) You didn't add parameter in your crontab." >> $LOGPATH/crontab.log
    echo "Syntax: backup.sh (db_rsync|www_rsync)" >> $LOGPATH/crontab.log
  ;;
esac

exit 0