知識儲備:node
一、Rsync是Unix/Linux下的一款應用軟件,利用它可使多臺服務器數據保持同步一致性,第一次同步時 rsync 會複製所有內容,但在下一次只傳輸修改過的文件。Rsync 在傳輸數據的過程當中能夠實行壓縮及解壓縮操做,所以可使用更少的帶寬。能夠很容易作到保持原來文件的權限、時間、軟硬連接等。web
二、Inotify是一個 Linux特性,它監控文件系統操做,好比讀取、寫入和建立。Inotify反應靈敏,用法很是簡單,而且比 cron 任務的繁忙輪詢高效得多。Rsync安裝完畢後,須要安裝inotify文件檢查軟件。vim
說明:準備兩臺服務器node1和node2,node1:202.207.178.6爲服務端,node2:202.207.178.7爲客戶端服務器
1、配置rsync,實現主從數據同步ssh
node1上:ide
編譯安裝rsync:ui
前提:須要裝開發環境:# yum -y install gccspa
一、下載並安裝rsyncorm
# wget http://rsync.samba.org/ftp/rsync/src/rsync-3.0.7.tar.gz遞歸
# tar xf rsync-3.0.7.tar.gz
# cd rsync-3.0.7
# ./configure --prefix=/usr/local/rsync
# make && make install
二、編輯配置文件
# vim /etc/rsyncd.conf
添加如下內容:
#########[global] 全局配置
uid = nobody
gid = nobody
use chroot = no
max connections = 30
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log
transfer logging = yes
log format = %t %a %m %f %b
syslog facility = local3
timeout = 300
[web]
read only = yes
path = /data/www/web
comment = web
auth users =fsy
secrets file = /etc/rsync.pas
hosts allow = 202.207.178.0/24
釋義:
[www] #要同步的模塊名
path = /data/www/web #要同步的目錄
comment = web #這個名名稱無所謂,最好與模塊名保持一致
read only = no # no客戶端可上傳文件,yes只讀
write only = no # no客戶端可下載文件,yes不能下載
list = yes #是否提供資源列表
auth users =test #登錄系統使用的用戶名,沒有默認爲匿名。
hosts allow = 202.207.178.0/24 #本模塊容許經過的IP地址
hosts deny = IP() #禁止主機IP
secrets file=/etc/rsync.pas #密碼文件存放的位置
三、建立所需文件和目錄
建立祕鑰文件,並修改其權限
# vim /etc/rsync.pas
fsy:fsy666
# chmod 700 /etc/rsync.pas
四、啓動rsync服務,並查看是否正常啓動
# /usr/local/rsync/bin/rsync --daemon
# ps -ef | grep rsync
五、在服務器端建立複製目錄,並在其中放置文件
# mkdir -pv /data/www/web
至此服務端配置完畢!
node2上:
一、創建祕鑰文件,並受權
# vim /etc/rsync.pas
fsy666
# chmod 600 /etc/rsync.pas
二、鏈接至服務器端進行同步
# rsync -aP --delete fsy@202.207.178.6::web /data/www/web --password-file=/etc/rsync.pas
此時在從服務器能夠看到拷貝的文件!
釋義:
-a, --archive歸檔模式,表示以遞歸方式傳輸文件,並保持全部文件屬性。
--exclude=PATTERN指定排除一個不須要傳輸的文件匹配模式
--exclude-from=FILE從 FILE 中讀取排除規則
--include=PATTERN指定須要傳輸的文件匹配模式
--delete刪除那些接收端還有而發送端已經不存在的文件
-P等價於 --partial --progress,實現半同步複製
-v, --verbose詳細輸出模式
-q, --quiet精簡輸出模式
--rsyncpath=PROGRAM指定遠程服務器上的 rsync 命令所在路徑
--password-file=FILE從 FILE 中讀取口令,以免在終端上輸入口令,一般在 cron 中鏈接 rsync 服務器時使用
2、經過Inotify實現數據實時同步(在node1上安裝)
一、實現雙機互信
node1:
# ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
# ssh-copy-id -i .ssh/id_rsa.pub root@202.207.178.7
node2:
# ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
# ssh-copy-id -i .ssh/id_rsa.pub root@202.207.178.6
二、安裝inotify-tools-3.14.tar.gz
# tar xf inotify-tools-3.14.tar.gz
# cd inotify-tools-3.14
# ./configure
# make && make install
三、配置auto_inotify.sh同步腳本
# vim auto_inotify.sh
內容以下:
#!/bin/sh
src=/data/www/web/
des=/data/www/web/
ip=202.207.178.7
inotifywait -mrq --timefmt '%d/%m/%y-%H:%M' --format '%T %w%f' -e modify,delete,create,attrib ${src} | while read file
do
for i in $ip
do
/usr/local/rsync/bin/rsync -aP --delete $src root@$ip:$des
done
done
四、在服務器端後臺啓動該腳本
# nohup sh auto_inotify.sh &
此時在主服務器上的/data/www/web作修改,會發現從服務器上的/data/www/web也作一樣的改動,說明配置成功!
歡迎批評指正!