Linux监控文件变化及主动上报实现
一、说明
最近在做一些主机的自动化检查操作,每次都是定时主动去扫描。这种方式一是实时性不佳,二是扫描时会陡然给中心机很大的压力。后来想有没有一种主机上的配置如果发生变动就能主动上报的机制,如果能主动上报一又解决了实时性问题,二也解决了中心机压力的问题。
二、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) [ ~]# 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 event3.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