一、說明
最近在做一些主機的自動化檢查操作,每次都是定時主動去掃描。這種方式一是實時性不佳,二是掃描時會陡然給中心機很大的壓力。后來想有沒有一種主機上的配置如果發生變動就能主動上報的機制,如果能主動上報一又解決了實時性問題,二也解決了中心機壓力的問題。
二、Shell腳本實現
2.1 基本使用
安裝:
yum install inotify-tools
使用格式:
# 使用格式 inotifywait [-hcmrq] [-e <event> ] [-t <seconds> ] [--format <fmt> ] [--timefmt <fmt> ] <file> [ ... ] # 最常用格式舉例 # 持續監控/etc/passwd文件被修改事件 inotifywait -m -e modify /etc/passwd # 持續監控/tmp目錄及其子目錄下的所有事件 inotifywait -m -r /tmp
2.2 實現示例
在一個終端窗口中開啟監控:
在另外一個終端窗口中執行命令:
再回頭看第一個窗口,顯示如下:
三、Python實現
3.1 基本使用
安裝:
pip install pyinotify
使用格式:
(base) [root@ls-virtual-machine ~]# python -m pyinotify -h Usage: pyinotify.py [options] [path1] [path2] [pathn] Options: -h, --help show this help message and exit -v, --verbose Verbose mode -r, --recursive Add watches recursively on paths -a, --auto_add Automatically add watches on new directories -g, --glob Treat paths as globs -e EVENT[,...], --events-list=EVENT[,...] A comma-separated list of events to watch for - see the documentation for valid options (defaults to everything) -s, --stats Display dummy statistics -V, --version Pyinotify version -f, --raw-format Disable enhanced output format. -c COMMAND, --command=COMMAND Shell command to run upon event
3.2 使用示例
在一個終端窗口中開啟監控:
在另一個終端窗口中執行命令:
再回頭看第一個窗口,顯示如下:
3.3 代碼使用示例
將以下代碼保存成test.py:
import pyinotify # Watch Manager wm = pyinotify.WatchManager() # 監聽文件創建事件和文件刪除事件 mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE class EventHandler(pyinotify.ProcessEvent): # 如果文件創建事件發生,則要執行的代碼 def process_IN_CREATE(self, event): print(f"Creating: {event.pathname}") # 如果文件刪除事件產生,則要執行的代碼 def process_IN_DELETE(self, event): print(f"Removing: {event.pathname}") handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('/tmp', mask, rec=True) # 持續監控 notifier.loop()
在一個終端窗口中運行該文件:
在另一個終端窗口中執行命令:
再回頭看第一個窗口,顯示如下:
參考:
https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes