1. 程式人生 > >rsync + inotify 打造多server間文件實時同步

rsync + inotify 打造多server間文件實時同步

events temp 登陸 family 機器 reat 3.1 height 一個

在上篇文章ssh無password登陸server的基礎之上。能夠利用rsync + Inotify 在多server間實現文件自己主動同步。

例如以下測試機基於三臺server做的。內網IP分別例如以下:

172.16.3.91 (主機)

172.16.3.92 (備份機1)

172.16.3.89 (備份機2)


如今想對主機上的/opt/sites/yutian_project文件夾下相關文件的不論什麽操作同步到2臺備份機上。

1.安裝rsync

在三臺機器上分別檢查是否安裝了rsync

[[email protected] ~]# rsync --version

rsync version 2.6.8 protocol version 29

Copyright (C) 1996-2006 by Andrew Tridgell, Wayne Davison, and others.

<http://rsync.samba.org/>

Capabilities: 64-bit files, socketpairs, hard links, ACLs, xattrs, symlinks, batchfiles,

inplace, IPv6, 64-bit system inums, 64-bit internal inums


rsync comes with ABSOLUTELY NO WARRANTY. This is free software, and you

are welcome to redistribute it under certain conditions. See the GNU

General Public Licence for details.


若沒有安裝,安裝下。因為安裝過程比較簡單,就不介紹了。

1.查看內核是否支持Inotify特性.

Inotify 是一種強大的、細粒度的、異步的文件系統事件監控機制,linux內核從2.6.13起,加入了Inotify支持。通過Inotify能夠監控文件系統中加入、刪除。改動、移動等各種細微事件,利用這個內核接口,第三方軟件就能夠監控文件系統下文件的各種變化情況,而inotify-tools就是這種一個第三方軟件。

[[email protected] ~]# ll /proc/sys/fs/inotify

total 0

-rw-r--r-- 1 root root 0 May 8 08:20 max_queued_events

-rw-r--r-- 1 root root 0 May 8 08:20 max_user_instances

-rw-r--r-- 1 root root 0 May 8 08:20 max_user_watches

能看到這個三個文件,說明是默認支持lnotify特性的。

2.安裝inotify-tools

下載地址:http://sourceforge.net/projects/inotify-tools/

下載之後編譯安裝

[[email protected] download]$ tar -zxvf inotify-tools-3.13.tar.gz

[[email protected] inotify-tools-3.13]$ ./configure

[[email protected] inotify-tools-3.13]$ make

[[email protected] inotify-tools-3.13]$ sudo make install


安裝之後生成例如以下2個命令

[[email protected] inotify-tools-3.13]$ inotifywa

inotifywait inotifywatch


如今編寫同步shell腳本

[[email protected] work]$ vi inotify_rsync_multl.sh


#!/bin/sh

#set -x

#var

src="/opt/sites/yutian_project/apps /opt/sites/yutian_project/statics /opt/sites/yutian_project/templates"

des_ip="172.16.3.92 172.16.3.89"

#function

inotify_fun ()

{

/usr/local/bin/inotifywait -mrq -e modify,delete,create,move $1 | while read time file

do

for ip in $des_ip

do

echo "`date +%Y%m%d-%T`: rsync -avzq --delete --progress $1 $ip:/opt/sites/yutian_project"

rsync -avzq --exclude=logs/* --delete --progress $1 $ip:/opt/sites/yutian_project/

echo

done

done

}

#main

for a in $src

do

inotify_fun $a &

done


運行inotify_rsync_multi.sh就能夠了。

如今主機上的相應文件夾上有不論什麽操作,就會同步到備份機上。


rsync + inotify 打造多server間文件實時同步