Linux + inotify實現監控文件變化及主動上報


一、說明

最近在做一些主機的自動化檢查操作,每次都是定時主動去掃描。這種方式一是實時性不佳,二是掃描時會陡然給中心機很大的壓力。后來想有沒有一種主機上的配置如果發生變動就能主動上報的機制,如果能主動上報一又解決了實時性問題,二也解決了中心機壓力的問題。

 

二、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

https://weizhimiao.github.io/2016/10/29/Linux%E4%B8%AD%E9%80%9A%E8%BF%87inotify-tools%E5%AE%9E%E7%8E%B0%E7%9B%91%E6%8E%A7%E6%96%87%E4%BB%B6%E5%8F%98%E5%8C%96/

https://github.com/seb-m/pyinotify/wiki


免責聲明!

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



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