linux下两台服务器文件实时同步方案实现-乾颐堂

时间:2023-03-08 20:34:23

假设有如下需求:

假设两个服务器:

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

http://www.qytang.com/
http://www.qytang.com/cn/list/28/358.htm
http://www.qytang.com/cn/list/41/
http://www.qytang.com/cn/list/37/
http://www.qytang.com/cn/list/46/
http://www.qytang.com/cn/page/19.htm
http://www.qytang.com/cn/list/32/
http://www.qytang.com/cn/list/28/
http://www.qytang.com/cn/list/25/
http://www.qytang.com/cn/list/28/625.htm
http://www.qytang.com/cn/list/28/612.htm