1. 程式人生 > >linux下rsync+inotify實現兩臺伺服器檔案實時同步

linux下rsync+inotify實現兩臺伺服器檔案實時同步

假設兩個伺服器:

192.168.0.1 源伺服器  有目錄 /opt/test/

192.168.0.2 目標伺服器  有目錄 /opt/bak/test/

實現的目的就是保持這兩個伺服器某個檔案目錄保持實時同步


實現方式: 通過rsync+inotify-tools結合來實現
需要安裝軟體:

1.  rsync 同步軟體


   在 源伺服器 和 目標伺服器 都需要安裝

  
   源伺服器: 是rsync客戶端,不需要配置

 目標伺服器: 是rsync伺服器端,需要配置/etc/rsyncd.conf裡的內容


  安裝後需要新建配置檔案:/etc/rsyncd.conf

  配置檔案在: /etc/


檔案內容如下:

uid = root
gid = root
use chroot = no
max connections = 10
strict modes = yes
pid file=/var/run/rsyncd.pid
lock file=/var/run/rsyncd.lock
log file= =/var/run/rsyncd.log

[www]
path= /opt/bak/test
comment= analyse
read only = false
hosts allow = *

2.  inotify-tools 工具

該工具為檔案實時監控工具,需要linux作業系統核心支援,核心支援需要至少版本為2.6.13

檢查作業系統是否支援,執行如下:

uname -r  檢視版本

返回:

2.6.32-220.4.1.el6.x86_64


則表示版本2.6.32 大於2.6.13,則支援。

執行:

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後會在相關安裝目錄下生成如下兩個檔案:

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

#!/bin/bash
src=/opt/test/

#每次啟動時校驗主備檔案差異
/usr/bin/rsync -arzuqt --delete --include "upload_approve/" --include "dbbak/" --exclude "/*" $src 192.168.0.2::www/

/usr/local/inotify/bin/inotifywait -mrq --timefmt '[%Y/%m/%d %H:%M:%S]' --format '%T %w%f %e' --excludei "dat/" --excludei "datbk/" --excludei "logbk/" --excludei "log/" -e modify,create,delete,attrib $src |  while read file
do   
      /usr/bin/rsync -arzuqt --delete --include "upload_approve/" --include "dbbak/" --exclude "/*"  $src 192.168.0.2::www/

      echo "  ${file} was rsynced" >>/opt/soft/log/rsync.log 2>&1
done

注意: 這裡的 www 是在目標伺服器/etc/rsyncd.conf裡配置的模組名稱:[www]

賦予執行許可權: chmod +x  inotify_bak.sh

然後執行: inotify_bak.sh &  放入後臺執行

4. 關於啟動

   目標伺服器:先啟動rsync後臺服務: /usr/bin/rsync --daemon

   來源伺服器: 執行 inotify_bak.sh & 


5. 測試:

   在來源伺服器目錄中新建目錄和檔案,inotify_bak.sh指令碼會檢測到,然後同步到目標伺服器的相關目錄下

 
   可以檢視日誌檔案: /opt/soft/log/rsync.log 命令如下:觀察實時同步的情況。

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