inotify+unison雙向同步環境部署

在網上搜尋了不少方案,在liux下作文件同步,有以下幾種方式: html

一、nfs實現web數據共享
二、rsync +inotify實現web數據同步
三、rsync+sersync更快更節約資源實現web數據同步
四、unison+inotify實現web數據雙向同步 linux

在這裏詳細介紹第四種方案,前幾種都有些各自的不足。只有第四種方案支持雙向實時同步,且當其中一臺服務器宕機,也不會影響web的訪問。(ps:以前一直喜歡nfs,配置很是簡單,可是其有個致命的缺點就是其中一臺web服務掛掉以後,會直接致使web頁面沒法訪問)。 web


環境部署,有以下兩臺服務器須要作雙向同步 shell

192.168.10.1是server1, bash

192.168.10.2是server2 服務器


第一步,保證兩臺服務器之間能夠經過ssh無密碼訪問,操做以下(這裏以root用戶爲例): ssh

分別在server1和server2下,建立祕鑰 測試

mkdir ~/.ssh
chmod 700 ~/.ssh
生成RSA密鑰
ssh-keygen -t rsa 
(而後連續三次回車)
加密

添加密鑰到受權密鑰文件中
spa

cd ~/.ssh
ssh "-p 22" 192.168.10.1 cat /root/.ssh/id_rsa.pub >> authorized_keys  #小寫p
ssh "-p 22" 192.168.10.2 cat /root/.ssh/id_rsa.pub >> authorized_keys
scp  -P 22 authorized_keys 192.168.10.2:/root/.ssh/  #大寫P

chmod 600 /root/.ssh/authorized_keys
在服務器server2上操做
chmod 600 /root/.ssh/authorized_keys
分別在兩臺機器上執行以下測試
ssh -p 22 192.168.10.1 date
ssh -p 22 192.168.10.2 date

至此用戶受權完成。

第二步,軟件安裝,server1和server2都得安裝

安裝unison
首先安裝ocaml,版本至少爲3.07或更高
下載地址:http://caml.inria.fr/pub/distrib/ocaml-3.10/
tar xf ocaml-3.10.2.tar.gz
cd ocaml-3.10.2
./configure
make world opt
make install
cd ..


安裝unison

下載地址:http://www.seas.upenn.edu/~bcpierce/unison//download/releases/unison-2.13.16/
tar xvf unison-2.13.16.tar.gz
cd unison-2.13.16
make UISTYLE=text THREADS=true STATIC=true
cp unison /usr/local/bin
cd ..


安裝inotify

下載地址:http://inotify-tools.sourceforge.net
tar xvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure
make
make install
cd ..


到此所需的軟件都已安裝完畢,能夠在server1服務器上執行這個命令,來查看兩臺服務器之間是否能夠同步文件,unison -batch /home/server1/ ssh://192.168.10.2//home/server2 ,若是這時候抱以下錯誤:


/usr/local/bin/inotifywait: error while loading shared libraries: libinotify
能夠執行下這個命令:



ln -sv /usr/local/lib/libinotify* /usr/lib/

執行成功後,看目錄下的文件是否同步。


第三步,建立.sh腳原本執行同步

1)server1上建立腳本/root/inotify.sh(chmod a+x /root/inotify.sh):


#/bin/bash
ip2="192.168.10.2"
src2="/home/server1/"
dst2="/home/server2/"
/usr/local/bin/inotifywait -mrq -e create,delete,modify,move $src2 | while read line; do
/usr/local/bin/unison -batch $src2 ssh://$ip2/$dst2
echo -n "$line " >> /var/log/inotify.log
echo `date | cut -d " " -f1-4` >> /var/log/inotify.log
done

1)server2上建立腳本/root/inotify.sh(chmod a+x /root/inotify.sh):

#/bin/bash 
ip1="192.168.10.1"
src1="/home/server2/"
dst1="/home/server1/"
/usr/local/bin/inotifywait -mrq -e create,delete,modify,move $src1 | while read line; do
/usr/local/bin/unison -batch $src1 ssh://$ip1/$dst1
echo -n "$line " >> /var/log/inotify.log
echo `date | cut -d " " -f1-4` >> /var/log/inotify.log
done
最後分別在server1和server2上執行上面兩個腳本,這樣兩臺服務器的目錄會保持相互實時同步了!!!
相關文章
相關標籤/搜索