shell脚本实现两台机器之间同步不再更改文件
代码功能,实现两台机器之间文件同步。遍历源目录所有文件,将写入完成的文件同步到目标机器。并将源文件删除。脚本定时启动,其同时判断之前脚本是否运行完。主体代码如下:
#!/bin/bash
#源文件所在目录
spath="/opt/testavor/*"
#目标主机名
host=1.1.*.*
#目标主机名密码
password='************'
#目标文件目录
path="/data/datatmp/avrosource"
#间隔时间设置单位秒
its=10
for file in $spath
do
if [ -d "$file" ]
then
continue
else
if [ -f "$file" ]
then
echo "$file"
#获取文件最后修改时间时间戳
lasttime=$(stat -c %Y "$file")
#当前时间戳
nowdate=$(date +%s)
#获得最后修改时间与现在时间的间隔
ts=$((nowdate-lasttime))
#判断文件最后修改时间间隔是否小于设置值单位秒
if (("$ts" <= "$its"))
then
continue
else
if (("$ts" >= "$its"))
then
/usr/bin/expect <<-EOF
set time 1
spawn scp $file root@$host:$path
expect "*password:"
send "$password\r"
expect eof
EOF
#是否删除源文件
#rm -f $file
fi
fi
fi
fi
done
启动代码如下:
#!/bin/bash
#同步脚本全路径
scpfilePath=/opt/testflile/scpfile.sh
pid=`ps -ef | grep $scpfilePath | grep -v "grep" | awk 'END{print $2}'`
echo $pid
if [ ! $pid ];then
echo "start boot..."
sh $scpfilePath
else
echo "scpfile.sh同步脚本正在运行"
fi