本文的程序与服务器运维同步备份脚本 打包篇联合使用,用来同步文件数据,数据库请使用主从热备到备份主机上。同步所使用的配置文件已在打包篇中列出,可对照使用。同步程序是利用rsync进行同步,可以对配置文件中指定的目录排序,详细代码如下:

#!/bin/bash
# By Chen.Zhidong
# http://sillydong.com
# Email:njutczd+gmail.com

PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH

PASSFILE="/etc/rsync.pas"
LOCAL_WWW="/home/www/"
TAG=$(date +%Y%m%d)
LOGDIR="/home/logs"
PIDFILE="./rsyncpid"

DAY_WEEK="5"
DAY_MONTH="26"

#Begin
readset(){
    #readset keywork setfile
    grep $1 $2 | grep -v "^#" | sed "s/$1=//"
}

www_rsync(){
    #www_rsync setfile
    www_dir=$LOCAL_WWW/`readset WWWNAME $1`
    rsyncip="`readset RSYNCIP $1`"
    rsyncname="`readset RSYNCNAME $1`"
    rsyncextra="`readset RSYNCEXTRA $1`"

    eval "rsync -auHzSv --bwlimit=512 --delete $rsyncextra --delete-excluded --ignore-errors --partial --password-file=$PASSFILE $www_dir rsync://rsyncback@${rsyncip}/${rsyncname}"
}

echo "rsync start at $(date)" >> $LOGDIR/rsyncback_${TAG}.log

if [ -e $PIDFILE ];then
    if [ "`cat $PIDFILE`" = "1" ];then
        echo "rsync is still running" >> $LOGDIR/rsyncback_${TAG}.log
        exit 0
    fi
else
    echo "1" > $PIDFILE
fi

if [ -e $LOGDIR/rsyncback_$(date +%Y%m%d --date="5 days ago").log ];then
    rm -f $LOGDIR/rsyncback_$(date +%Y%m%d --date="5 days ago").log
fi

LIST=`find $LOCAL_WWW -maxdepth 2 -name tar.set`
for setfile in $LIST
do
    echo -e "----\nusing $setfile" >> $LOGDIR/rsyncback_${TAG}.log
    if [ "`readset DORSYNC $setfile`" = "true" ];then
        frequency=`readset TARSET $setfile`
        case $frequency in
        daily)
            www_rsync $setfile >> $LOGDIR/rsyncback_${TAG}.log
            ;;
        weekly)
            if [ $(date +%w) = $DAY_WEEK ];then
                www_rsync $setfile >> $LOGDIR/rsyncback_${TAG}.log
            else
                echo "weekly skip $setfile" >> $LOGDIR/rsyncback_${TAG}.log
            fi
            ;;
        monthly)
            if [ $(date +%d) = $DAY_MONTH ];then
                www_rsync $setfile >> $LOGDIR/rsyncback_${TAG}.log
            else
                echo "monthly skip $setfile" >> $LOGDIR/rsyncback_${TAG}.log
            fi
            ;;
        *)
            echo "wrong frequency setting" >> $LOGDIR/rsyncback_${TAG}.log
            ;;
        esac
    else
        echo "skip" >> $LOGDIR/rsyncback_${TAG}.log
    fi
done

rm -f $PIDFILE
echo -e "----\nrsync done at $(date)" >> $LOGDIR/rsyncback_${TAG}.log
exit 0
#End