rsync+inotify實現服務器間文件的實時同步

    rsync雖然可以實現觸發式的文件同步,但是通過crontab守護進程方式進行觸發,同步的數據和實際數據會有差異,而inotify可以監控文件系統的各種變化,當文件有任何變動時,就觸發rsync同步,這樣剛好解決了我的需求,同步數據實時性的問題,下面便看我娓娓道來。

一) lists

Ip

Status

Cp  PATH

App

192.168.1.1

Server

/data

Rsync-server

192.168.1.2

Client

/OM/logs/data

Rsync-client+inotify

二)需求

    server端服務器(192.168.1.1)像client端服務器(192.168.1.2)同步數據,並讓inotify監聽操作。

    如果client端的/OM/logs/data下面有創建、刪除等文件操作,server端也會相應的實時同步數據文件。

 

三)實戰

Server:1.創建rsync主配置文件rsyncd.conf

 [email protected] :/etc# vi /etc/rsyncd.conf
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
max connections = 100
use chroot = no
uid = root
gid = root
ignore errors
list = no
[example]
path = /OM/logs/data
read only = no                    #no客戶端可上傳文件,yes只讀
write only = no                    #no客戶端可下載文件,yes不能下載
auth users = aaron              # 認證的用戶名,如果沒有這行,則表明是匿名
secrets file = /etc/rsyncd.passwd        # 指定認證口令文件位置
hosts allow = 192.168.1.2
hosts deny = *

          2.創建密碼驗證文件,rsyncd.passwd

[email protected]:/etc# vi rsyncd.passwd   
aaron:bu/I*)NEj

          3.修改密碼文件權限 

chmod 600 rsync.passwd

          4.啓動Rsync

 /usr/bin/rsync --daemon

Client:1,創建密碼驗證文件rsyncd.passwd,這裏只需要輸入密碼就可以了。

# vi rsyncd.passwd   
bu/I*)NEj

         2.安裝inotify

  1. [[email protected] ]# cd /app
    [[email protected]  app]# wget http://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz  
    [[email protected]  app]# tar zxvf inotify-tools-3.14.tar.gz  
    [[email protected]  app]# cd inotify-tools-3.14  
    [[email protected] inotify-tools-3.14]# ./configure --prefix=/usr/local/inotify  
    [[email protected] inotify-tools-3.14]# make  
    [[email protected] inotify-tools-3.14]# make install

        3.創建同步腳本

#!/bin/bash
host=192.168.1.1
src=/data
des=example
user=aaron
/usr/local/inotify/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e modify,delete,create,attrib $src | while read files
do
/usr/bin/rsync -vzrtopg --delete  --progress --password-file=/etc/rsyncd.passwd $src $user@$host::$des
echo "${files} was rsynced" >>/var/log/rsync.log 2>&1
done

        4.修改腳本權限並運行

chmod 764 rsync.sh
nohup rsync.sh &

        5.講腳本加入開機啓動項

echo "/usr/local/inotify/rsync.sh" >> /etc/rc.local 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章