Rsync+Inotify 搭建实时同步数据
1.安装软件包
# yum install inotify-tools # yum -y install rsync
2.同步机器相互添加信任
[root@host-10-0-100-106 ~]# ssh-keygen #一路回车 [root@host-10-0-100-106 ~]# ssh-copy-id -i /root/.ssh/ [root@host-10-0-100-106 ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.0.100.139
3.两台机器上分别放置同步脚本
vim /shell/inotify.sh
#!/bin/bash watch_dir=/data/wwwroot/www.ikmak.com/data/attachment push_to=10.0.100.104 #另一台机器放置修改ip地址 inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir --timefmt '%Y-%m-%d %H:%M:%S' --format '%w%f:%e:%T' $watch_dir \ --exclude=".*.swp" |\ while read line;do # logging some files which has been deleted and moved out if echo $line | grep -i -E "delete|moved_from";then echo "$line" >> /etc/inotify_away.log fi # from here, start rsync's function rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir $push_to:/data/wwwroot/www.ikmak.com/data/ if [ $? -eq 0 ];then echo "sent $watch_dir success" else echo "sent $watch_dir failed" fi done
优化脚本
[root@xuexi tmp]# cat ~/inotify.sh
#!/bin/bash
watch_dir=/www
push_to=172.16.10.5
# First to do is initial sync
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir $push_to:/tmp
inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir --timefmt '%Y-%m-%d %H:%M:%S' --format '%w%f:%e:%T' $watch_dir \
--exclude=".*.swp" >>/etc/inotifywait.log &
while true;do
if [ -s "/etc/inotifywait.log" ];then
grep -i -E "delete|moved_from" /etc/inotifywait.log >> /etc/inotify_away.log
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir $push_to:/tmp
if [ $? -ne 0 ];then
echo "$watch_dir sync to $push_to failed at `date +"%F %T"`,please check it by manual" |\
mail -s "inotify+Rsync error has occurred" root@localhost
fi
cat /dev/null > /etc/inotifywait.log
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir $push_to:/tmp
else
sleep 1
fi
done
4.配置后台执行脚本
# nohup /shell/inotify.sh &
# crontab -e * * * * * nohup /shell/inotify.sh > /dev/null 2>&1 &

浙公网安备 33010602011771号