rsync+inotify 实现实时同步

rsync+inotify 实现实时同步

1、安装rsync


可以通过yum源安装rsync服务
[root@dg test]# yum install rsync


也可以通过安装源码包
 wget  http://rsync.samba.org/ftp/rsync/src/rsync-3.0.9.tar.gz 
[root@dg test]#tar zxvf rsync-3.0.9.tar.gz 
[root@dg test]#cd rsync-3.0.9 
[root@dg test]#./configure --prefix=/usr/local/rsync 
[root@dg test]# make 
[root@dg test]#make install 


make -j 4 # make编译,将源代码编译成二进制,可执行的文件 -j 4 使用4个进程同时编译,考虑cpu个数,不要超过cpu的个数

例如:在源端有个目录/tmp/test下有文件,都会同步目标端10.10.6.82:/data下,但是此方式只能手工同步,不能实现实时同步
[root@dg test]# rsync -azP --delete /tmp/test [email protected]:/data

注:rsync 是基于ssh 协议,需要知道对服务器端的root和密码
-a, archive(存档) 归档模式,表示以递归的方式传输文件,并且保持稳健的属性,等同于加了参数-riptgoD
-z --compress 表示压缩
-P 显示传输速度
--delete 删除那些目标端位置有而原始位置没有的文件


添加ssh密钥服务,下次可以不用输入密码
[root@dg bin]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
1e:5f:6e:fe:15:a6:c1:12:d7:1d:4c:79:c5:9f:a3:9d root@dg

拷贝信任关系到目标端

[root@dg .ssh]# ssh-copy-id [email protected]


查看目标段密钥已经过去
[root@rac2 .ssh]# ls
authorized_keys  known_hosts

不用输入密码登录10.10.6.82,此方式同步不用输入密码
[root@dg .ssh]# ssh [email protected]
Last login: Wed Jan 20 10:42:22 2016 from 10.10.8.54
[root@rac2 ~]#


2 安装inotify


[root@dg test]#tar zxvf inotify-tools-3.14.tar.gz 
[root@dg test]# cd inotify-tools-3.14 
[root@dg test]# ./configure --prefix=/usr/local/inotify 
[root@dg test]# make 
[root@dg test]# make install

inotifywait -mrq -e create,move,delete,modify /tmp/test
-e 用来指定要监控哪些事件 这些事件包括 create,创建,move 移动,delete 删除,modify修改内容 attrib 属性的更改
-m 表示持续监控
-r表示递归监控
-q表示简化输出信息


另外开了一个窗口:
root@dg test]# cp /etc/group  /tmp/test
[root@dg ~]# inotifywait -mrq -e create,move,delete,modify /tmp/test
/tmp/test/ CREATE group
/tmp/test/ MODIFY group

从此可以看出 inotifywait 可以捕捉到创建文件的消息


3 创建rsync复制脚本


此项功能主要是将server端的目录/tmp里的内容,如果修改了(无论是添加、修改、删除文件)能够通过inotify监控到,并通过rsync实时的同步给client的/tmp里,下面是通过shell脚本实现的。


[root@dg test]# cat rsync.sh
#!/bin/bash 
host=10.10.6.82
src=/data 
des=/data2
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  $src $user@$host:$des 
echo "${files} was rsynced" >>/rsync.log 2>&1 
done

其中host是client的ip,src是server端要实时监控的目录,des是认证的模块名,需要与client一致,user是建立密码文件里的认证用户。
把这个脚本命名为rsync.sh,放到监控的目录里,比如我的就放到/tmp下面,并给予764权限,建议各位吧rsync的日志放到其他的目录下(非备份目录)。
[root@dg test]# chmod 764 rsync.sh


然后运行这个脚本
[root@dg test]#  sh /tmp/rsync.sh &


我们还可以把rsync.sh脚本加入到开机启动项里
echo "/tmp/rsync.sh" >> /etc/rc.local

在源端目录添加或者删除文件,目标端的文件夹也会改变

Rsync 的详细介绍请点这里
Rsync 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-01/127803.htm