inotify-tools的inotifywait工具用exclude 和 fromfile 排除指定后缀文件

今天打算使用 inotify-tool 来对线上程序文件进行监控, 因为有些目录是缓存目录, 所以要进行排除, 同时还要排除一些指定的后缀的文件, 比如 .swp 等

需要递归监控的目录为: /tmp/inotify-test-dir
需要排除的目录为: /tmp/inotify-test-dir/cache
需要排除特定后缀文件: .log .swp 文件

根据网上看的一些资料, 我先做了如下尝试:

/usr/local/bin/inotifywait -mr -e close_write,modify,create,move,delete --exclude ^.*\.(log|swp)$ --exclude "^/tmp/inotify-test-dir/cache" --timefmt %Y/%m/%d %H:%M --format %T %w%f %e /tmp/inotify-test-dir

发现无论如何改, 第一个排除指定后缀 .log 和 .swp 都不生效, 我以为是我写的正则有问题, 又修改了很多次, 还是不行. 没办法再次google, 最终还是让我发现了问题的所在, 原来 inotifywait 不支持两次 --exclude , 否则,后面的规则将覆盖前面的规则.

明白问题的所在后, 再次修改:

/usr/bin/inotifywait -mr -e modify,create,move,delete --exclude '^/tmp/inotify-test-dir/(cache|(.*/*\.log|.*/*\.swp)$)' --timefmt '%Y/%m/%d %H:%M' --format '%T %w%f %e' /tmp/inotify-test-dir

这次ok 通过

-----------
inotifywait 有 --fromfile 选项, 可以直接从文件中读入要监控的目录,和排除的目录. 在这里我使用 --fromfile '/tmp/inotify-file-list' 选项

/tmp/inotify-file-list 文件的内容如下:

/tmp/inotify-test-dir
@/tmp/inotify-test-dir/cache

以@开头的路径代表的是要排除的目录和文件,其他的为要监控的文件

假如:我要递归监控 /tmp/inotify-test-dir 目录下的所有的所有的 .php 文件, 但是排除 /tmp/inotify-test-dir/cache 目录下的所有文件

我就可以这样写

/usr/bin/inotifywait -mr -e modify,create,move,delete --exclude ^.+\.[^php]$ --fromfile '/tmp/inotify-file-list' --timefmt '%Y/%m/%d %H:%M' --format '%T %w%f %e'

注意:
1、此种写法可以不用加“/tmp/inotify-test-dir”路径,fromfile中写有即可,经测试,加“/tmp/inotify-test-dir”路径也是可以正常运行
2、fromfile指向的文件,刚开始我是Notepad++创建,不知道是因为文件格式问题还是什么原因,导致在文件中写的规则出现莫名其妙的问题,后来通过touch命令新建一个文件,然后再在里面写入规则,测试后全部正常,害我白研究了一天时间。

附我在生产服务器上的自动同步脚本

#!/bin/sh
SRC=/data/wwwroot/web/ #代码发布服务器目录
DST=/data/wwwroot/web/ #目标服务器目录
IP="192.168.20.7"    #目标服务器IP,多个以空格隔开
USER=www
INOTIFY_EXCLUDE="--fromfile /data/conf/shell/inotify_exclude.list"
RSYNC_EXCLUDE="--include-from=/data/conf/shell/rsync_include.list --exclude-from=/data/conf/shell/rsync_exclude.list"

#su - $USER
inotifywait -mrq --exclude "(.swp|.inc|.svn|.rar|.tar.gz|.gz|.txt|.zip|.bak)" -e modify,delete,create,close_write,attrib $INOTIFY_EXCLUDE | while read D E F  
	do  
		for i in $IP
		do
			/usr/bin/rsync -e 'ssh -p 5000' -ahqzt $RSYNC_EXCLUDE --delete $SRC $USER@$i:$DST			
		done		
	done

参考资料:
inotifywait exclude 排除指定后缀文:http://blog.chaiyalin.com/2014/02/inotifywait-exclude.html

发表评论?

3 条评论。

  1. 你好我使用unison和inotify-tool实现同步。
    (1)将执行脚本放到rc.local让它开机自启后,仍然无法实现同步,必须使用nohup /root/inotify.sh &执行脚本才能实现同步。
    (2)在rc.local中,用nohup /root/inotify.sh &,重启后仍然无法同步。但是进程确实打开了。而且执行inotify.sh脚本,每次监测的文件夹发生变化,就会记录日志,我查看日志它是有记录内容的,说明它inotifywait是可以响应的。但就是不去执行文件同步。
    (3)我注释了rc.local中的nohup /root/inotify.sh &,在终端执用nohup执行这个脚本,它也是可以同步的。
    这种情况是怎么回事?我查看文档,看着将执行脚本放到rc.local中它就应该能同步,而且我使用su 执行脚本,它同样不能同步。 最后一个问题:nohup.out文件感觉增大的很快,还没怎么测试已经将近20M了。这样不好吧?

  2. ^.+\.[^php]$

    这个断言,文件名中出现p|h|p的文件不会被排除掉!

回复给 三木 ¬
取消回复

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据