需求背景
公司有八臺nginx服務器用來做靜態文件服務器和http請求轉發,所以當需要修改nginx配置文件或者部署靜態文件的時候,需要分別修改八臺機器上的文件,費時費力。
最終目的
對其中某一個機器的某些文件夾做監控,只要其中的內容有發生修改,其餘機器馬上同步這些修改到自己的機器上
實現工具
rsync+inotify
實現步驟
-
主服務器A安裝rsync
$ yum install rsync
-
寫配置文件,需要自己建文件夾和文件
$ cd /etc/rsync.d $ touch rsyncd.secret
rsyncd.secret文件內容如下:
admin123 //後面其他服務器要同步此服務器文件需要用到的密碼
-
安裝inotify工具
yum install inotify-tools
-
編寫實現同步的腳本,這個腳本的作用就是通過inotify監控本服務器某個文件目錄的變化,進而觸發其他host進行rsync同步操作
$ cd /etc/inotify $ touch inotify.sh
inotify.sh文件內容如下:
#!/bin/bash host="10.104.xx.xxx 10.104.xx.xxx 10.104.xx.xxx" src=/data/web/html dst=htmlFile user=root pass_file=/etc/rsync.d/rsyncd.secrets /usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib $src | while read files do for hostip in $host do /usr/bin/rsync -vzrtopg --delete --progress --password-file=$pass_file $src $user@$hostip::$dst done echo "${files} was rsynced" >>/tmp/rsync.log 2>&1 done
-
同步服務器B、C、D安裝rsync
$ yum install rsync
-
寫配置文件,需要自己建文件夾和文件
$ cd /etc/rsync.d $ touch rsyncd.conf rsyncd.secret rsyncd.motd
rsyncd.conf是配置文件,內容如下
uid = root gid = root use chroot = yes max connections = 100 pid file = /var/run/rsyncd.pid log file = /var/log/rsyncd.log motd file = /etc/rsync.d/rsyncd.motd [htmlFile] path = /data comment = Rsync html file uid = root gid = root auth users = root secrets file = /etc/rsync.d/rsyncd.secrets read only = yes list = yes ignore errors read only = no write only = no hosts allow = xx.xxx.xx.xx (主服務器A的host)
rsyncd.secret是密碼文件,內容如下
root:admin123
rsyncd.motd是服務器描述文件,內容如下
++++++++++++++++++++++++++++++++++++ This is Server B, Welcome! +++++++++++++++++++++++++++++++++++++
-
將rsyncd.secrets這個密碼文件的文件屬性設爲root擁有, 且權限要設爲600, 否則無法備份成功
$ chmod 600 rsyncd.secrets
-
啓動rsync服務器(daemon參數方式,是讓rsync以服務器模式運行)
/usr/bin/rsync --daemon --config=/etc/rsync.d/rsyncd.conf
-
設置開機啓動rsync服務
echo “/usr/bin/rsync --daemon --config=/etc/rsync.d/rsyncd.conf >/dev/null &”>>/etc/rc.local