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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM