Debian系统监控文件状态的常用方法
inotify-tools是Debian系统原生支持的文件监控工具集,基于Linux内核的inotify
机制,能实时监控文件/目录的创建、修改、删除等事件,适合大多数日常需求。
sudo apt update && sudo apt install inotify-tools
inotifywait -m /path/to/file -e modify,attrib,close_write
(-m
表示持续监控,-e
指定事件类型);inotifywait -m -r /path/to/directory -e create,delete,modify
(-r
表示递归)。inotifywait -m -r /path/to/dir -e create,delete,modify --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S'
;.tmp
结尾的文件):inotifywait -m -r /path/to/dir -e create,delete,modify --exclude '.*\.tmp$'
;inotifywait
输出重定向到日志文件,或添加邮件/短信通知逻辑。fswatch是跨平台的文件系统监控工具,支持Linux、macOS、Windows等系统,适合需要跨环境使用的场景。
sudo apt update && sudo apt install fswatch
fswatch /path/to/file
;fswatch -r /path/to/directory
(-r
表示递归);fswatch -r -i 1s /path/to/directory
(-i
指定间隔时间)。watch是Debian系统自带的命令行工具,通过定期执行指定命令(如ls
、stat
)来间接监控文件状态,适合简单的周期性检查需求。
watch -n 5 ls -l /path/to/file
其中,-n 5
表示每5秒执行一次ls -l
命令,显示文件的详细信息(如权限、大小、修改时间),通过对比输出变化判断文件是否被修改。auditd是Linux内核的审计系统,能详细记录文件访问、修改、删除等操作的审计日志,适合需要合规性或详细追踪的场景(如追踪谁修改了文件)。
sudo apt update && sudo apt install auditd audispd-plugins
;/etc/passwd
文件):sudo auditctl -w /etc/passwd -p wa -k passwd_changes
(-w
指定监控路径,-p wa
表示监控写入和属性修改,-k
设置规则标签);sudo ausearch -k passwd_changes
(ausearch
命令用于查询审计日志)。若需要更灵活的监控逻辑(如特定文件类型的过滤、网络通知),可以使用Python结合watchdog
库实现。
pip install watchdog
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
print(f"文件 {event.src_path} 已创建")
def on_deleted(self, event):
print(f"文件 {event.src_path} 已删除")
def on_modified(self, event):
print(f"文件 {event.src_path} 已修改")
if __name__ == "__main__":
path = "/path/to/directory"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
将脚本保存为monitor.py
,运行后即可监控指定目录的文件变化(支持创建、删除、修改等事件)。