rsync + inotify 打造多server间文件实时同步

在上篇文章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

[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就能够了。

如今主机上的相应文件夹上有不论什么操作,就会同步到备份机上。


原文地址:https://www.cnblogs.com/yxysuanfa/p/6950707.html