Debian 文件变化监控实用指南
一 常用工具与适用场景
二 快速上手命令示例
sudo apt-get update
sudo apt-get install -y inotify-tools
inotifywait -m -e modify,attrib,close_write,move,create,delete /path/to/file
inotifywait -m -r -e modify,create,delete,move /path/to/dir --format '%T %w%f %e' --timefmt '%F %T'
sudo apt-get install -y fswatch
fswatch -r /path/to/dir
# 以 NUL 分隔事件,便于 while read -d '' 处理
fswatch -0r /path/to/dir | while IFS= read -r -d '' ev; do echo "Event: $ev"; done
sudo apt-get install -y entr
# 当 .c 文件变化时执行 make
ls /src/*.c | entr -p make
watch -n 2 ls -l /path/to/file
以上命令覆盖从“实时事件流”到“触发式执行”的常见用法,可直接复制到终端测试。
三 长期运行与系统服务化
#!/usr/bin/env bash
file="/tmp/test.txt"
log="/tmp/filewatch.log"
inotifywait -m -e modify "$file" | while read -r _ action _; do
echo "$(date '+%F %T'): $file changed ($action)" >> "$log"
# 可在此加入重启服务、同步、告警等动作
done
[Unit]
Description=Watch /tmp/test.txt changes
[Path]
PathChanged=/tmp/test.txt
[Install]
WantedBy=multi-user.target
[Unit]
Description=Action when /tmp/test.txt changes
[Service]
Type=oneshot
ExecStart=/usr/bin/bash -c 'echo "$(date ''+%%F %%T''): /tmp/test.txt changed" >> /tmp/filewatch.log'
sudo systemctl daemon-reload
sudo systemctl enable --now filewatch.path
该方式由 systemd 托管,具备日志、依赖、开机自启与进程守护能力,适合替代手写 while 循环。
四 审计级监控与日志查询
sudo apt-get install -y auditd audispd-plugins
sudo systemctl enable --now auditd
# 监控单个文件
echo '-a exit,always -F path=/path/to/file -k file_change' | sudo tee -a /etc/audit/rules.d/file-mon.rules
# 如需递归监控目录,可按需添加多条规则或使用通配(谨慎性能影响)
sudo augenrules --load
sudo ausearch -k file_change
五 选型建议与注意事项