rsync+inotify实现文件时实同步[转]

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://linux008.blog.51cto.com/2837805/595922

1、说明
   实验操作系统:CentOS release 5.6
   服务器端(代码更新服务器):192.168.0.5
   客户端(web服务器):192.168.0.6   192.168.0.7  192.168.0.8
   web目录:/data/httpd/wwwroot/
   原理:由192.168.0.5上inotify服务监测文件是否有更新,如果有更新(修改,删除,新建)inotify就会通过rsync命令将更新的文件推向三台web服务器
   架构图如下:

2、在三台web上配置rsync服务

   #mkdir -p /data/httpd/wwwroot       #创建web目录

   #vim /etc/rsyncd.conf               #配置文件
   uid = root
   gid = root
   use chroot = no
   max connections = 5
   pid file = /var/run/rsyncd.pid
   lock file = /var/run/rsync.lock
   log file = /var/log/rsyncd.log

   [www]
   path=/data/httpd/wwwroot/
   comment = update
   ignore errors
   read only = no
   list = no
   hosts allow = 192.168.0.0/255.255.255.0
   auth users = root
   uid = root
   gid = root
   secrets file = /etc/rsyncd.secrets
   
   #vim /etc/rsyncd.secrets                   #创建rsync证文件
   123456
   root:123456

   #chmod 0600 /etc/rsyncd.secrets            #设置权限
   #rsync --daemon                            #启动服务
   #echo "rsync --daemon"  >> /etc/rc.local   #开机自启动
  


   关于rsync详细配置请参考http://linux008.blog.51cto.com/2837805/570936
3、配置服务端(rsync+inotify)
   #mkdir -p /data/httpd/wwwroot   #创建目录存放代码
   (1)、安装inotify

   #cd /usr/local/src/
   #wget http://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
   #tar xzvf inotify-tools-3.14.tar.gz
   #cd inotify-tools-3.14
   #./configure
   #make
   #make install


   (2)、编写同步更新脚本

   #mkdir /root/bin
   #cd /root/bin
   #vim rsync.sh
   
   #!/bin/bash
   src=/data/httpd/wwwroot/
   des=www
   host="192.168.0.6 192.168.0.7 192.168.0.8"
   /usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib $src | while read files
   do
     for hostip in $host
     do
        rsync -vzrtopg --delete --progress --password-file=/etc/rsyncd.secrets $src root@$hostip::$des
     done
     echo "${files} was rsynced" >>/tmp/rsync.log 2>&1
   done


   (3)、创建rsync认证文件
   

   #vim /etc/rsyncd.secrets                 

   123456

   root:123456
   #chmod u+x /etc/rsyncd.secrets

   (4)、启动

   #nohup /bin/bash /root/bin/rsync.sh &

   
   (5)、开机自启动

   #echo "nohup /bin/bash /root/bin/rsync.sh &" >> /etc/rc.local

   
   (6)、测试
   在192.168.0.5上进入目录/data/httpd/wwwroot/
   #touch a.txt
   在三台web机上/data/httpd/wwwroot/目录可以立马看a.txt。

原文地址:https://www.cnblogs.com/jrsun/p/4010596.html