假設(shè)兩個(gè)服務(wù)器:172.16.0.1 源服務(wù)器有目錄 /opt/test/和172.16.0.2 目標(biāo)服務(wù)器有目錄 /opt/bak/test/,實(shí)現(xiàn)的目的就是保持這兩個(gè)服務(wù)器某個(gè)文件目錄保持實(shí)時(shí)同步。
實(shí)現(xiàn)方式: 通過(guò)rsync+inotify-tools結(jié)合來(lái)實(shí)現(xiàn)
準(zhǔn)備工作:
首先要給兩臺(tái)機(jī)器添加信任關(guān)系并免密碼登錄
接著需要安裝軟件:
1. rsync同步軟件
在源服務(wù)器和目標(biāo)服務(wù)器都需要安裝rsync
源服務(wù)器: 是rsync客戶端,不需要配置
目標(biāo)服務(wù)器: 是rsync服務(wù)器端,需要配置/etc/rsyncd.conf里的內(nèi)容
2. inotify-tools 工具
該工具為文件實(shí)時(shí)監(jiān)控工具,需要linux操作系統(tǒng)內(nèi)核支持,內(nèi)核支持需要至少版本為2.6.13
檢查操作系統(tǒng)是否支持,執(zhí)行如下:
uname -r 查看版本
返回:
2.6.32-358.6.1.el6.x86_64
則表示版本2.6.32 大于2.6.13,則支持。
執(zhí)行:
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
有三項(xiàng)輸出,則表示默認(rèn)支持inotify,可以安裝inotify-tools工具.
如果不支持,需要采用新版本的linux操作系統(tǒng)。版本達(dá)到要求,就可以安裝了。
安裝inotify-tools后會(huì)在相關(guān)安裝目錄下生成如下兩個(gè)文件:
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
則表示安裝成功。
注意: 在 源服務(wù)器上需要安裝,目標(biāo)服務(wù)器上不需要安裝inotify。
3. 相關(guān)腳本:
在源服務(wù)器上新建腳本:
inotify_bak.sh
#!/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 172.16.0.1::www/
echo " ${file} was rsynced" >>/opt/soft/log/rsync.log 2>&1
done
賦予執(zhí)行權(quán)限: chmod +x inotify_bak.sh
然后執(zhí)行:nohup inotify_bak.sh & 放入后臺(tái)執(zhí)行
4. 關(guān)于啟動(dòng)
目標(biāo)服務(wù)器:先啟動(dòng)rsync后臺(tái)服務(wù): /usr/bin/rsync --daemon
來(lái)源服務(wù)器: 執(zhí)行 inotify_bak.sh &
5. 測(cè)試:
在來(lái)源服務(wù)器目錄中新建目錄和文件,inotify_bak.sh腳本會(huì)檢測(cè)到,然后同步到目標(biāo)服務(wù)器的相關(guān)目錄下
可以查看日志文件: /opt/soft/log/rsync.log 命令如下:觀察實(shí)時(shí)同步的情況。
tail -f /opt/soft/log/rsync.log
錯(cuò)誤解決:
/usr/local/bin/inotifywait: error while loading shared libraries: libinotifytools.so.0: cannot open shared object file: No such file or directory
這是因?yàn)檎也坏綆?kù)文件的原因,做一個(gè)軟連接就好了
ln -s /usr/local/lib/libinotifytools.so.0 /usr/lib64/libinotifytools.so.0