linux下兩台服務器文件實時同步方案實現-乾頤堂


假設有如下需求:

假設兩個服務器:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM