一聚教程网:一个值得你收藏的教程网站

热门教程

CentOS下rsync+inotify-tools实现数据实时同步更新

时间:2022-06-30 20:57:38 编辑:袖梨 来源:一聚教程网

rsync优点:安全性高、备份速度快、支持增量备份等。inotify是细密度的、异步的文件系统事件监控机制,Linux内核从2.6.13起,加入了对inotify的支持,通过第三方软件inotify-tools可以监控文件系统下的文件的各种变化情况。

rsync和inotify-tools的配合使用可以实现数据的实时同步更新。以下是配置过程。

环境说明

Server A ip address :192.168.2.102
Server B ip address :192.168.2.103

Server A的rsync服务配置

安装rsync

这里直接使用yum安装rsync。

yum -y install xinetd rsync
sed -i '/disable/s/yes/no/g' /etc/xinetd.d/rsync
/etc/init.d/xinetd restart > /dev/null

建立rsync主配文件:rsyncd.conf

uid = root
gid = root
use chroot = no
max connections = 200
port = 873
timeout = 600
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

[wwwroot]
path = /data/wsdata/wwwroot/
comment = This is test
auth users = backupadmin
ignore errors
read only = no
list = no
hosts allow = 192.168.2.0/255.255.255.0
secrets file = /etc/rsync.pas

创建rsync认证文件:sync.pas

【格式】 用户:密码文件

vim /etc/rsync.pas

backadmin:password

chmod 600 rsync.pas
启动服务rsync服务

rsync --daemon
Server B的rsync服务配置

安装rsync,跟Server A一样的方法。

yum -y install xinetd rsync
sed -i '/disable/s/yes/no/g' /etc/xinetd.d/rsync
/etc/init.d/xinetd restart > /dev/null

建立密码文件,密码文件权限:600

vim /etc/rsync.pas

password

chmod 600 /etc/rsync.pas

rsync同步文件方法

从Server A服务器上下载

rsync -vzrtopg --delete --progress --password-file=/etc/rsync.pas backupadmin@192.168.2.102::wwwroot /data/wsdata/wwwroot/

上传到Server A服务器

rsync -vzrtopg --delete --progress --password-file=/etc/rsync.pas /data/wsdata/wwwroot backupadmin@192.168.2.102::wwwroot
inotify-tools实现实时同步更新

以下配置全部在Server B服务器上操作。

下载安装inotify-tools

wget https://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
tar zxvf inotify-tools-3.14.tar.gz
cd inotify-tools
./configure && make && make install
Server B的inotify监控脚本

vim rsync_inotify.sh
#!/bin/bash
src=/data/wsdata/wwwroot/

/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y/%H:%M' --format '%T %w %f' -e modify,delete,create,attrib $src | while read file
do
rsync -vzrtopg --delete --progress --password-file=/etc/rsync.pas $src backupadmin@192.168.2.102::wwwroot
echo "$src was rsynced"
done

注意:目录/data/wsdata/wwwroot/末尾一定加斜杠 “/”

-m 是保持一直监听
-r 是递归查看目录
-q 是打印出事件
--timefmt 是指定时间的输出格式
--format 指定文件变化的详细信息
-e create,move,delete,modify,attrib 是指 “监听 创建 移动 删除 写入 权限” 事件
执行脚本

nohup ./rsync_inotify.sh &

nohup 命令运行由 Command 参数和任何相关的 Arg 参数指定的命令,忽略所有挂断(SIGHUP)信号。在注销后使用 nohup 命令运行后台中的程序。要运行后台中的 nohup 命令,添加 & ( 表示“and”的符号)到命令的尾部。

执行后的结果是Server B上更新了文件,会自动同步到Server A上。

如果出现这个错误“/usr/local/bin/inotifywait: error while loading shared libraries:
libinotifytools.so.0”可以采用以下办法解决:

ln -sv /usr/local/lib/libinotify* /usr/lib/

热门栏目