rsync实时同步

 

假设有如下需求:

假设两个服务器:

192.168.0.1 源服务器  有目录 /opt/test/

192.168.0.2 目标服务器  有目录 /opt/bak/test/

实现的目的就是保持这两个服务器某个文件目录保持实时同步

 

实现方式: 通过rsync+inotify-tools结合来实现

准备工作:

首先要给两台机器添加信任关系,具体方法已经在前面的文章介绍过了

详情查看: linux添加信任关系免密码登录

需要安装软件:

1.  rsync 同步软件

    在 源服务器 和 目标服务器 都需要安装

    源服务器: 是rsync客户端,不需要配置

    目标服务器: 是rsync服务器端,需要配置/etc/rsyncd.conf里的内容

2.  inotify-tools 工具

    该工具为文件实时监控工具,需要linux操作系统内核支持,内核支持需要至少版本为2.6.13

    检查操作系统是否支持,执行如下:

    uname -r  查看版本

    返回:

1
     2.6.32-358.6.1.el6.x86_64

    则表示版本2.6.32 大于2.6.13,则支持。

    执行:

1
2
3
4
5
     ll  /proc/sys/fs/inotify
     total 0
     -rw-r--r-- 1 root root 0 Oct 18 12:18 max_queued_events
     -rw-r--r-- 1 root root 0 Oct 18 12:18 max_user_instances
     -rw-r--r-- 1 root root 0 Oct 18 12:18 max_user_watches

    有三项输出,则表示默认支持inotify,可以安装inotify-tools工具.

 

    如果不支持,需要采用新版本的linux操作系统

    版本达到要求,就可以安装了。

    安装inotify-tools后会在相关安装目录下生成如下两个文件:

1
2
3
4
     ll  /usr/local/bin/
     total 88
     -rwxr-xr-x 1 root root 44327 Oct 10 15:32 inotifywait
     -rwxr-xr-x 1 root root 41417 Oct 10 15:32 inotifywatch

    则表示安装成功。

    注意: 在 源服务器上需要安装,目标服务器上不需要安装inotify。

3. 相关脚本:

    在源服务器上新建脚本:

    inotify_bak.sh

1
2
3
4
5
6
7
     #!/bin/bash
     src= /opt/test/
     /usr/local/bin/inotifywait  -mrq --timefmt  '%d/%m/%y %H:%M'  -- format  '%T %w%f%e'  -e close_write,delete,create,attrib $src |   while  read  file
     do
           /usr/bin/rsync  -arzuq $src 192.168.0.1::www/
           echo  "  ${file} was rsynced"  >> /opt/soft/log/rsync .log 2>&1
     done

    赋予执行权限: chmod +x  inotify_bak.sh

    然后执行:nohup inotify_bak.sh &  放入后台执行

4. 关于启动

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

    来源服务器: 执行 inotify_bak.sh & 

 

5. 测试:

    在来源服务器目录中新建目录和文件,inotify_bak.sh脚本会检测到,然后同步到目标服务器的相关目录下

 

    可以查看日志文件: /opt/soft/log/rsync.log 命令如下:观察实时同步的情况。

1
     tail  -f   /opt/soft/log/rsync .log

错误解决:

/usr/local/bin/inotifywait: error while loading shared libraries: libinotifytools.so.0: cannot open shared object file: No such file or directory

这是因为找不到库文件的原因,做一个软连接就好了

1
ln  -s  /usr/local/lib/libinotifytools .so.0  /usr/lib64/libinotifytools .so.0

转载于:https://www.cnblogs.com/guarderming/p/10929081.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值