Inotify+Rsync实现Linux文件实时同步

发表于:2010-3-03 10:58

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

分享:

  三、使用

  1.查看是否支持inotify,从kernel 2.6.13开始正式并入内核,RHEL5已经支持。看看是否有 /proc/sys/fs/inotify/目录,以确定内核是否支持inotify

[root@RHEL5 Rsync]# ll /proc/sys/fs/inotify
total 0
-rw-r--r-- 1 root root 0 Oct  9 09:36 max_queued_events
-rw-r--r-- 1 root root 0 Oct  9 09:36 max_user_instances
-rw-r--r-- 1 root root 0 Oct  9 09:36 max_user_watches

  2.关于递归:

  inotifywait

  This command simply blocks for inotify events, making it appropriate for use in shell scripts. It can watch any set of files and directories, and can recursively watch entire directory trees.

  3.使用:

#!/bin/sh
src=/opt/webmail
des=/tmp
ip=192.168.7.192
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format  '%T %w%f' \
-e modify,delete,create,attrib \
${src} \
| while read  file
     do
        rsync -avz --delete --progress ${src} root@${ip}:${des} &&
        echo "${src} was rsynced"
        echo "-------------------------------------------------"
     done

  注:当要排出同步某个目录时,为rsync添加--exculde=PATTERN参数,注意,路径是相对路径。详细查看man rsync

  当要排除都某个目录的事件监控的处理时,为inotifywait添加--exclude或--excludei参数。详细查看man inotifywait

另:/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' \
-e modify,delete,create,attrib \
${src} \

  上面的命令返回的值类似于:

  10/03/09 15:31 /wwwpic/1

  这3个返回值做为参数传给read,关于此处,有人是这样写的:

  inotifywait -mrq -e create,move,delete,modify $SRC | while read D E F;do细化了返回值。

  注:要取得监控文件发生的事件,在--format处指定%e参数,同时,使用--event参数来指定要监控的事件即可,如--format '%T %w%f %e' --event modify,delete,create,attrib

  说明:当文件系统发现指定目录下有如上的条件的时候就触发相应的指令,是一种主动告之的而非我用循环比较目录下的文件的异动,该程序在运行时,更改目录内的文件时系统内核会发送一个信号,这个信号会触发运行rsync命令,这时会同步源目录和目标目录。

  --timefmt:指定输出时的输出格式

  --format: '%T %w%f'指定输出的格式,上面的输出类似于:12/10/08 06:34 /opt/webmail/dovecot-1.1.2/src/test/1

  小脚本,同步到多台主机:

文件:
inotify_rsync.tar.gz
大小:
1KB
下载:
下载

  更改后,更简单,适用于同步到相同的目录,监控多目录,多文件,同步到多台服务器

#!/bin/sh
#set -x
#var
src="/usr/local/nginx/html/lib /usr/local/nginx/html/www /usr/local/nginx/html/var/www.work.com.conf.php"
des_ip="172.18.1.35 172.18.1.36 172.18.1.37 172.18.1.38"
#function
inotify_fun ()
{
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y-%H:%M' --format '%T %w%f' \
-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:`dirname $1`"
rsync -avzq --delete --progress $1 $ip:`dirname $1`
echo
done
done
}
#main
for a in $src
do
inotify_fun $a &
done

  参考:http://www.ibm.com/developerworks/cn/linux/l-ubuntu-inotify/index.html

32/3<123>
重磅发布,2022软件测试行业现状调查报告~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号