rsync + inotify 制作多服务器间文件实时同步

rsync + inotify 打造多服务器间文件实时同步

在上篇文章ssh无密码登陆服务器的基础之上,可以利用rsync + Inotify 在多服务器间实现文件自动同步。

如下测试机基于三台服务器做的,内网IP分别如下:

172.16.3.91    (主机)

172.16.3.92 (备份机1)

172.16.3.89 (备份机2)


现在想对主机上的/opt/sites/yutian_project目录下相关文件的任何操作同步到2台备份机上。

1.安装rsync

在三台机器上分别检查是否安装了rsync

[root@rs-1 ~]# 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就是这样的一个第三方软件。

[root@rs-1 ~]# 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/

下载之后编译安装

[vagrant@rs-1 download]$ tar -zxvf inotify-tools-3.13.tar.gz

[vagrant@rs-1 inotify-tools-3.13]$ ./configure 

[vagrant@rs-1 inotify-tools-3.13]$ make 

[vagrant@rs-1 inotify-tools-3.13]$ sudo make install


安装之后生成如下2个命令

[vagrant@rs-1 inotify-tools-3.13]$ inotifywa

inotifywait   inotifywatch  


现在编写同步shell脚本

[vagrant@rs-1 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就可以了。现在主机上的对应目录上有任何操作,就会同步到备份机上。