贝利信息

Linux怎么监控文件变化_Linux inotify文件监控工具使用【实时】

日期:2026-01-15 00:00 / 作者:尼克
Linux中可用inotify机制毫秒级监控文件操作:一、检查内核CONFIG_INOTIFY_USER=y;二、安装inotify-tools;三、用inotifywait命令实时监听;四、Shell脚本自动响应事件;五、Python pyinotify库实现高级监控。

如果您需要在Linux系统中实时捕获文件或目录的创建、修改、删除等操作,则可借助内核原生支持的inotify机制实现毫秒级响应。以下是多种可行的监控方法:

一、确认内核是否启用inotify支持

inotify自Linux 2.6.13起内建于内核,但需验证当前运行内核是否已编译启用该功能。若未启用,后续所有用户态工具均无法工作。

1、执行命令:grep CONFIG_INOTIFY_USER /boot/config-$(uname -r)

2、若输出为CONFIG_INOTIFY_USER=y,表示支持可用;若无输出或显示=n,则需升级内核或重新配置编译选项。

二、安装inotify-tools命令行工具集

inotify-tools提供轻量、易用的命令行接口,无需编程即可完成基础监控任务,是日常运维首选。

1、Debian/Ubuntu系统执行:sudo apt update && sudo apt install inotify-tools

2、CentOS/RHEL 8+系统执行:sudo dnf install inotify-tools

3、CentOS/RHEL 7系统执行:sudo yum install inotify-tools

4、验证安装:运行inotifywait --version,确认版本号正常输出。

三、使用inotifywait命令行实时监控

inotifywait支持阻塞式监听,可直接在终端输出事件详情,适合调试与简单自动化场景。

1、监控单个文件内容修改:inotifywait -m -e modify /etc/hosts

2、递归监控整个目录及其子目录的所有常见变更:inotifywait -m -r -e create,delete,modify,move,attrib /var/www/html

3、输出带时间戳和完整路径的简洁日志:inotifywait -m --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w%f %e' -e modify /tmp/config.yaml

四、编写Shell脚本实现自动响应

将inotifywait与shell逻辑结合,可在事件触发时立即执行任意命令,如重载服务、写入日志或调用API。

1、创建脚本文件:nano ~/watch_nginx.sh

2、写入以下内容:
#!/bin/bash
while inotifywait -e modify /etc/nginx/nginx.conf >/dev/null; do
  nginx -t && systemctl reload nginx
done

3、赋予执行权限:chmod +x ~/watch_nginx.sh

4、后台运行:nohup ~/watch_nginx.sh &

五、使用Python pyinotify库实现高级监控

pyinotify支持路径过滤、多事件组合判断、异步处理及集成进大型项目,适用于需复杂逻辑的生产环境。

1、安装库:pip install pyinotify

2、创建监控脚本:nano ~/py_monitor.py

3、填入代码:
import pyinotify
class EventHandler(pyinotify.ProcessEvent):
  def process_IN_MODIFY(self, event):
    if event.pathname.endswith('.conf'):
      print(f"[CONF MODIFIED

] {event.pathname}")
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, EventHandler())
wm.add_watch('/etc', pyinotify.IN_MODIFY, rec=True)
notifier.loop()

4、运行脚本:python ~/py_monitor.py