inotify+rsync实现文件双向实时同步

1.先安装rsync

yum install rsync //这里由于在docker里测试的,用yum安装包,可使用其他安装方式

2.创建rsync的配置文件

vi /etc/rsyncd.conf


motd file = /etc/rsyncd.motd
uid=root
gid=root
max connections=36000
use chroot=no
log file=/var/log/rsyncd.log
log format = %t %a %m %f %b
pid file=/var/run/rsyncd.pid
lock file=/var/run/rsyncd.lock
timeout = 300

#同步模块
[tongbu]
path=/var/www/html  #同步的目录
list=yes
comment = this is comment 
ignore errors = yes
read only = no
hosts allow = 172.17.0.3  #允许同步的服务器ip
hosts deny = *
auth users backup   #授权同步用户

3.创建同步用户

useradd backup  //创建用户
passwd backup   //设置密码

4.启动服务

/usr/bin/rsync --daemon --config=/etc/rsyncd.conf

ps -ef |grep rsyncd #查看服务是否启动

5.在另外一台服务器,重新来一遍上面的操作,配置文件指定另一台的ip。

/usr/bin/rsync -vzrtopg --delete --progress /var/www/html/ backup@172.17.0.3::tongbu --password-file=/etc/rsync.password  #执行同步
--password-file 为同步用户的密码

这样在一台服务器新建文件,另外一台可同步创建。

inotify可实时监控文件目录变化事件,可以利用Inotify来实现实时同步

创建同步脚本

vi inotify.sh

#!/bin/bash
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib /var/www/html/ | while read file   #监听目录的modify,delete,create,attrib事件
do
/usr/bin/rsync -vzrtopg --delete --progress /var/www/html/ backup@172.17.0.3::tongbu --password-file=/etc/rsync.password   #执行同步

echo "${files} was rsynced" >> /var/log/rsync.log 2>&1
done

 多台服务器可实时多向同步 


原文地址:https://www.cnblogs.com/oceanL/p/14072037.html