inotify+rsync實現檔案雙向實時同步
1.先安裝rsync
yum install rsync //這裡由於在docker裡測試的,用yum安裝包,可使用其他安裝方式
2.建立rsync的配置檔案
vi /etc/rsyncd.conf
motd file = /etc/rsyncd.motd
uid=root
gid=root
max connections=36000
use chroot=no
log file=/var/log/rsyncd.log
log format = %t %a %m %f %b
pid file=/var/run/rsyncd.pid
lock file=/var/run/rsyncd.lock
timeout = 300
#同步模組
[tongbu]
path=/var/www/html #同步的目錄
list=yes
comment = this is comment
ignore errors = yes
read only = no
hosts allow = 172.17.0.3 #允許同步的伺服器ip
hosts deny = *
auth users backup #授權同步使用者
3.建立同步使用者
useradd backup //建立使用者
passwd backup //設定密碼
4.啟動服務
/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
ps -ef |grep rsyncd #檢視服務是否啟動
5.在另外一臺伺服器,重新來一遍上面的操作,配置檔案指定另一臺的ip。
/usr/bin/rsync -vzrtopg --delete --progress /var/www/html/ backup@172.17.0.3::tongbu --password-file=/etc/rsync.password #執行同步
--password-file 為同步使用者的密碼
這樣在一臺伺服器新建檔案,另外一臺可同步建立。
inotify可實時監控檔案目錄變化事件,可以利用Inotify來實現實時同步
建立同步指令碼
vi inotify.sh
#!/bin/bash
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib /var/www/html/ | while read file #監聽目錄的modify,delete,create,attrib事件
do
/usr/bin/rsync -vzrtopg --delete --progress /var/www/html/ [email protected]::tongbu --password-file=/etc/rsync.password #執行同步
echo "${files} was rsynced" >> /var/log/rsync.log 2>&1
done
多臺伺服器可實時多向同步