rsync+inotify实现服务器之间文件互相同步(实时)

inotify链接:https://github.com/rvoicilas/inotify-tools

A、B两台服务器之间相互做服务端-客户端的策略

实验机器:CentOS 7:192.168.71.65、Ubuntu 16.04:192.168.71.195

同步目录为/root/test/

两端文件名称基本相同,所有文件处于root目录下

服务端文件:

密码认证文件:

rsync-server.passwd 内容:123456 权限600

脚本rsync.sh: 权限764

#!/bin/bash
host=192.168.71.*
src=/root/test/
des=web
user=root
/usr/local/inotify/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e modify,delete,create,attrib $src | while read files
do
/usr/bin/rsync -vzrtopg --delete --progress --password-file=/root/rsync-server.passwd $src $user@$host::$des
echo "${files} was rsynced" >>/root/rsync.log 2>&1
done

客户端文件:

密码认证文件:

rsync-client.passwd 内容:root:123456 权限600

配置文件:rsync.conf

内容:

uid = root
gid = root
use chroot = no
max connections = 10
strict modes = yes
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
[web] #此处为模块名称,与服务端脚本相同
path = /root/test/
comment = web file #描述,可自定义
ignore errors
read only = no
write only = no
hosts allow = 192.168.71.* 白名单
hosts deny = * 黑名单
list = false
uid = root
gid = root
auth users = root
secrets file = /root/rsync-client.passwd

启动,
先执行命令

rsync --daemon --config=/root/rsync.conf

再执行rsync.sh脚本

开机启动:

rsync --daemon --config=/root/rsync.conf
/root/rsync.sh &

rsync默认监听873端口

日志文件路径:/root/rsync.log为自定义日志,/var/log/rsyncd.log为标准日志

修改inotify默认参数(inotify默认内核参数值太小)

查看系统默认参数值

sysctl -a | grep max_queued_events

结果是:fs.inotify.max_queued_events = 16384

sysctl -a | grep max_user_watches

结果是:fs.inotify.max_user_watches = 8192

sysctl -a | grep max_user_instances

结果是:fs.inotify.max_user_instances = 128

修改参数:

sysctl -w fs.inotify.max_queued_events="99999999"
sysctl -w fs.inotify.max_user_watches="99999999"
sysctl -w fs.inotify.max_user_instances="65535"

/etc/sysctl.conf #添加以下代码

fs.inotify.max_queued_events=99999999
fs.inotify.max_user_watches=99999999
fs.inotify.max_user_instances=65535

参数说明:

max_queued_events:
inotify队列最大长度,如果值太小,会出现”** Event Queue Overflow **”错误,导致监控文件不准确

max_user_watches:
要同步的文件包含多少目录,可以用:find 同步目录 -type d | wc -l 统计,必须保证max_user_watches值大于统计结果

max_user_instances:
每个用户创建inotify实例最大值

 

单向同步

A服务器向B服务器传输
A 服务器文件
rsync-server.passwd (权限600)
rsync.sh

B服务器文件
rsync-client.passwd
rsync.conf

首先在B服务器中执行rsync –daemon –config=/root/rsync.conf
然后在A服务器中执行rsync.sh脚本文件

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注