歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> 學習Linux >> 實戰:rsync+inotify實現數據實時同步,rsyncinotify

實戰:rsync+inotify實現數據實時同步,rsyncinotify

日期:2017/3/3 18:08:56   编辑:學習Linux

實戰:rsync+inotify實現數據實時同步,rsyncinotify

實戰:rsync+inotify實現數據實時同步,rsyncinotify


Linux 內核從 2.6.13 版本開始提供了 inotify 通知接口,用來監控文件系統的各種變化情況,如文件存取、刪除、移動等。利用這一機制,可以非常方便地實現文件異動告警、增量備份,並針對目錄或文件的變化及時作出響應。可以監控某個用戶,什麼時間,做了什麼動作!利用這個內核接口,第三方軟件就可以監控文件系統下文件的各種變化情況,而inotify-tools正是實施監控的軟件。

  使用 rsync 工具與 inotify 機制相結合,可以實現觸發式備份(實時同步),只要原始位置的文檔發生變化,則立即啟動增量備份操作,否則處於靜態等侍狀態,這樣一來,就避免了按固定周期備份進存在的延遲性、周期過密等問題。

軟件下載地址:http://sourceforge.net/projects/inotify-tools/ #notify-tools-3.13

試驗要求:將test2主機/var/www/html目錄實時同步到test1主機/var/www/html目錄中;

試驗拓普圖

  [root@test2 ~]#uname -r #查看linux內核

   2.6.32-431.el6.x86_64

  [root@test2 ~]#yum -y install xinetd rsync; #安裝rsync服務

[root@test2 ~]#yum -y install gcc-c++,openssh-clients

將inotify-tools上傳並進行解壓安裝

  [root@test2 ~]# tar xvf inotify-tools-3.13.tar.gz -C /usr/local/src/ #解壓

  [root@test2 ~]# cd /usr/local/src/inotify-tools-3.13/ #切換目錄

  [root@test2 inotify-tools-3.13]#./configure --prefix=/usr/local/inotify-tools ; #編譯安裝

  [root@test2 inotify-tools-3.13]#make ; make install

測試

使用inotifywait命令監控網站目錄/var/www/html發生的變化,然後在另一個終端向/var/www/html目錄下添加文件、移動文件,查看屏幕輸出結果。

  inotifywait常用參數:

  -e 用來指定要監控哪些事件。這些事件包括: create 創建,move 移動,delete 刪除,modify 修改文件內容,attrib 屬性更改。

  -m 表示持續監控

  -r 表示遞歸整個目錄

  -q 表示簡化輸出信息

[root@test2 ~]# inotifywait -mrq -e create,move,delete,modify /var/www/html/

然後再另開一終端,進入/var/www/html目錄進行新增刪除測試;

  [root@test2 html]#mkdir test

  [root@test2 html]#touch test.txt

  [root@test2 html]#rm -rf test.txt

創建觸發式腳本自動同步數據

ssh免密碼登錄

  [root@test2~]#ssh-keygen #生成密鑰

  [root@test2~]#ssh-copy-id [email protected] #發布公鑰

編寫腳本

  [root@test2~]#vim inotify.sh

  #!/bin/bash

  SRC=/var/www/html

  [email protected]:/var/www/html

  inotifywait -mrq -e modify,delete,create,attrib ${SRC}|while read D E F

do

/usr/bin/rsync -avz --delete $SRC $DST

done

  [root@test2~]#chmod +x inotify.sh #添加執行權限

測試自動同步的效果

  [root@test2~]#./inotify.sh #運行腳本

  另開一終端進行新增刪除修改動作

  [root@test2~]#cd /var/www/html/

  [root@test2~]#touch bb.txt

 

然後登錄到192.168.1.190服務器進行查看備份目錄

  

http://xxxxxx/Linuxjc/1170155.html TechArticle

Copyright © Linux教程網 All Rights Reserved