1. 程式人生 > >Linux-13-Inotify+Rsync實時資料同步

Linux-13-Inotify+Rsync實時資料同步

配置前檢查

1.首先確定Rsync已經配置完成,客戶端可以向服務端推送檔案

[[email protected] ~]$ rsync -avzP ./syncdir [email protected]::syner --password-file=/etc/rsync.password
sending incremental file list
syncdir/

sent 52 bytes  received 12 bytes  42.67 bytes/sec
total size is 0  speedup is 0.00

具體配置可以參考以下部落格

2.檢視當前系統是否支援Inotify

[[email protected] ~]$ ls -l /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Sep 25 13:25 max_queued_events
-rw-r--r-- 1 root root 0 Sep 25 13:25 max_user_instances
-rw-r--r-- 1 root root 0 Sep 25 13:25 max_user_watches

如果出現上面三個檔案,說明系統支援Inotify

3.下載安裝Inotify

執行以下命令(由於資訊過多,這裡就不貼出來了)

yum install -y epel-release && yum update
yum install inotify-tools

配置Inotify

1.編寫Inotify實時監控指令碼

[[email protected] ~]$ mkdir -p /home/syner/r_inotify/
vi /server/scripts/inotify/inotify.sh
#!/bin/bash
#para
host01=2.2.2.6
src=/home/syner/
dst=syner
user=rsync_backup
rsync_passfile=/etc/rsync.password
inotify_home=/usr/src/kernels/2.6.32-754.3.5.el6.x86_64/

#judge
if [ ! -e "$src" ] \
|| [ ! -e "${rsync_passfile}" ] \
|| [ ! -e "/usr/bin/inotifywait" ] \
|| [ ! -e "/usr/bin/rsync" ];
then
  echo "Check File and Folder"
  exit 9
fi

/usr/bin/inotifywait -mrq --timefmt '%d%m%y %H:%M' --format '%T %w%f' -e close_write,delete,cr
eate,attrib $src | while read file
do
  cd $src && rsync -aruzR --delete ./r_inotify --timeout=100 -e 'ssh -p 52113'  
[email protected]
$host01:/home/syner/ >> /home/syner/inotify.log 2>&1 done exit 0

2.執行程式

[[email protected] ~]$ sh /server/scripts/inotify/inotify.sh &
[1] 8509
[[email protected] ~]$ ps -ef | grep inotify
syner     8509  8440  0 19:01 pts/2    00:00:00 sh /server/scripts/inotify/inotify.sh
syner     8510  8509  0 19:01 pts/2    00:00:00 /usr/bin/inotifywait -mrq --timefmt %d%m%y %H:%M --format %T %w%f -e close_write,delete,create,attrib /home/syner/
syner     8511  8509  0 19:01 pts/2    00:00:00 sh /server/scripts/inotify/inotify.sh
syner     8513  8440  0 19:01 pts/2    00:00:00 grep inotify

 測試是否成功

[[email protected] r_inotify]$ echo "test inotify" > test.txt
[[email protected] r_inotify]$ ll
total 4
-rw-rw-r-- 1 syner syner 13 Sep 25 19:02 test.txt
[[email protected] r_inotify]$ more test.txt 
test inotify

成功同步過去了

[[email protected] r_inotify]$ rm test.txt 
[[email protected] r_inotify]$ ll
total 0

也可以同步刪除