您的位置:首页 > 运维架构 > Shell

shell 监控文件更新并同步到其它机器

2015-07-01 13:53 459 查看
本Shell用于实时检测当前文件下的文件是否有更新,如果有则同步到其它服务器上

#! /bin/bash

KEY='/root/.ssh/id_rsa'

PORT=22

SSH_OPT=" -i $KEY -p $PORT"

CUR_DIR=`pwd`

//要保持同步的服务器IP,可以添加多个:

DST_IPS=('102.152.138.28');

//要同步的文件

FILES=('a.txt'

'b.txt'

'dir/dir1/c.txt'

)

# Check the file last change time

function getLastChangeTime()

{

time=`stat $1 | grep Change | awk '{print $3}'`

echo "$time"

}

# Distribute the new files to all servers

function sendToServers()

{

for ip in ${DST_IPS[*]}

do

strCount=`echo $1 | tr -cd '/' | wc -c `

dstDir=`echo $1 | cut -d '/' -f 1-$strCount`

# file=`echo $1 | cut -d '/' -f $strCount`

#echo directory is: $dstDir, file is $file

if [ "$dstDir" != "" ]; then

ssh $SSH_OPT root@$ip "mkdir -p $CUR_DIR/$dstDir"

fi

scp -i $KEY $1 root@$ip:$CUR_DIR/$dstDir/

if [ "$?" -eq "0" ]; then

echo "Copy $1 to remote $ip:$CUR_DIR/$dstDir done. "

else

echo "Copy $1 to remote $ip:$CUR_DIR/$dstDir failed!, try again later !"

return 1

fi

done

return 0

}

#kill previous running process

function killProcess()

{

for pid in `ps -ef |grep file_change_detect |grep -v grep |awk '{print $2}'`

do

echo "\n kill file_change_detect.sh ($pid)";

kill -9 $pid;

done

}

#Loop to detect file modifications

while((1))

do

count=0

for f in ${FILES[*]}

do

if [ ! -f "$f" ]; then

echo "Can not find file $f"

else

t="$(getLastChangeTime $f)"

if [ "${TIME[$count]}" != "$t" ]; then

echo "$f: Last change time: ${TIME[$count]}, New change time: $t "

sendToServers $f

if [ "$?" -eq "0" ]; then

TIME[$count]=`echo $t`;

echo "Pushed done and update file change time."

fi

fi

fi

let count++

done

sleep 3

echo "sleep 3 sec"

trap "killProcess; exit" 2

done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: