linux使用rsync、inotify-tools实现多台服务器文件实时同步

需求:将本地192.168.1.10上的/data/wwwroot目录同步到

1、来源服务器上安装rsync、inotify-tools

yum -y install rsync
yum -y install inotify-tools

2、新建同步脚本(inotify_bak.sh)

#!/bin/bash
src=/data/wwwroot/
des1=web1
des2=web2
des3=web3
host1=192.168.1.12
host2=192.168.1.13
host3=192.168.1.14
user1=web
user2=web
user3=web
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,delete,create,attrib $src | while read file DATE TIME DIR;
do
    /usr/local/rsync/bin/rsync -vzrtopg --delete --exclude-from=/etc/exclude.txt --progress $src $user1@$host1::$des1 --password-file=/etc/web.passwd
    /usr/local/rsync/bin/rsync -vzrtopg --delete --exclude-from=/etc/exclude.txt --progress $src $user2@$host2::$des2 --password-file=/etc/web.passwd
    /usr/local/rsync/bin/rsync -vzrtopg --delete --exclude-from=/etc/exclude.txt --progress $src $user3@$host3::$des3 --password-file=/etc/web.passwd
    echo "  ${file} was rsynced" >>/data/logs/rsync/rsync.log 2>&1
done

  上面的rsync和 inotifywait  的路径根据实际安装情况而定

  注意: 这里的 web 是在目标服务器/etc/rsyncd.conf里配置的模块名称:[web] (后面配置目标服务器会讲到)
  赋予执行权限: chmod +x  inotify_bak.sh

  新增密码文件:touch /etc/web.passwd 内容为密码 设置权限600
  新增排除文件:touch /etc/exclude.txt 内容为不需要同步的目录或者文件 (也可以实时--include-from=只同步那些目录或者文件) 
  例如:
    logs/
    rubbish/

3、目标服务器配置(需要同步的服务器)

  安装rsync 和 xinetd 

yum -y install  rsync xinetd
#安装后需要新建配置文件:
touch /etc/rsyncd.conf

  修改rsyncd内容:

#Global Settings 全局配置
uid = root                         
gid = root                         
use chroot = no                   
max connections = 5    
timeout = 600             
pid file = /var/run/rsyncd.pid
lockfile = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log
#模块配置
[web1]
path = /data/wwwroot/
ignore errors = yes
read only = no
write only = no
hosts allow = 192.168.1.10
hosts deny = *
list = yes
uid = root
gid = root
auth users = web
secrets file = /etc/web.passwd

  这里的配置的web1和users就是inotify_bak.sh里面的dest1和user1的值

  新增密码文件:内容 用户名:密码 设置权限600  例如:web:123456

  touch /etc/web.passwd 

  注意:这里的密码要跟来源服务器那台的密码文件的密码一样
  其他两台目标服务器也是同样的配置,然后都创建/data/wwwroot目录

4、启动运行

   目标服务器:先启动rsync后台服务: /usr/bin/rsync --daemon

     来源服务器: nohup inotify_bak.sh &  放入后台执行 

现在可以试试在来源服务器的/data/wwwroot目录里面新建一个文件,看是否会实时同步到其他三台。

猜你喜欢

转载自www.cnblogs.com/myIvan/p/9314694.html