1. 程式人生 > >inotify+rsync檔案實時同步

inotify+rsync檔案實時同步

需要程式碼釋出伺服器與需要同步的伺服器

釋出伺服器上下載

在程式碼釋出伺服器上安裝inotify,執行如下命令
wget https://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
tar xzvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure
make
make install
cd ..
安裝完畢 建立軟連線
ln -s /usr/local/lib/libinotifytools.so.0 /usr/lib64/libinotifytools.so.0

以下命令在每臺伺服器上都需要執行

在所有伺服器上安裝rsync,命令如下:
wget https://download.samba.org/pub/rsync/src/rsync-3.1.3.tar.gz
tar zxvf rsync-3.1.3.tar.gz
cd rsync-3.1.3
./configure
make
make install

免登陸配置

在程式碼釋出伺服器與需要同步的伺服器之間配置ssh key信任,在程式碼釋出伺服器上生成公鑰和私鑰
ssh-keygen -t rsa
直接三次回車
將公鑰新增到各個需要更新的主機authorized_keys 檔案中,在程式碼釋出伺服器上再執行
ssh-copy-id -i ~/.ssh/id_rsa.pub

[email protected]#需要同步的伺服器IP
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]#需要同步的伺服器IP

如果有提示 輸入yes
按提示輸入密碼回

//----------------------------------------------------------

在程式碼釋出伺服器上以root身份建立inotify_rsync.sh指令碼

mkdir /root/script
vi /root/script/inotify_rsync.sh 輸入

#!/bin/sh
SRC=/home/wwwroot/default/    #程式碼釋出伺服器目錄
DST=/home/wwwroot/default/    #目標伺服器目錄
IP="192.168.67.131 192.168.67.132"    #目標伺服器IP,多個以空格隔開
USER=root
/usr/local/bin/inotifywait -mrq --timefmt '%Y-%m-%d %H:%M' --format '%T %w%f %e' --exclude "(.swp|.swx|.svn)" \
-e create,move,delete,close_write,attrib $SRC | while read files
do
for i in $IP
do
    /usr/local/bin/rsync -ahqzt --exclude Runtime --delete $SRC 
[email protected]
$i:$DST echo $files >>/tmp/rsync.log 2>&1 done done 然後賦予指令碼可執行許可權 chmod +x /root/script/inotify_rsync.sh 設定開機自啟動 echo "/root/inotify_rsync.sh &" >> /etc/rc.local 執行指令碼/root/script/inotify_rsync.sh &

相關解釋:

-------------------實時同步----------------------
/usr/local/bin/inotifywait -mrq --timefmt ‘%Y-%m-%d %H:%M’ --format ‘%T %w%f %e’ --exclude “(.swp|.swx|.svn)”
-e create,move,delete,close_write,attrib $SRC | while read files

-m 是保持一直監聽
-r 是遞迴檢視目錄
-q 是打印出事件
-e create,move,delete,close_write,attrib 是指 “監聽 建立 移動 刪除 寫入 許可權” 事件

/usr/local/bin/rsync -ahqzt --exclude Runtime --delete $SRC U S E R @ [email protected] i:$DST
-a 存檔模式
-h 儲存硬連線
-q 制止非錯誤資訊
-z 壓縮檔案資料後傳輸
-t 維護修改時間
-delete 刪除於多餘檔案

–exclude 排除同步的檔案
-------------------實時同步解釋----------------------