Linux文件系统监控方法
inotify是Linux内核提供的文件系统事件监控机制,可实时捕获文件/目录的创建、删除、修改等事件,是Linux下最常用的实时监控方案。
inotify-tools(包含inotifywait和inotifywatch命令)。sudo apt-get install inotify-toolssudo yum install inotify-toolsinotifywait -m /path/to/directoryinotifywait -m -e create,delete,modify /path/to/directoryinotifywait -m -r /path/to/directoryinotifywatch -v -e modify,create,delete -t 60 /path/to/directoryfswatch是一个跨平台的文件系统监控工具,支持Linux、macOS、Windows等,功能强大且易于使用。
sudo apt-get install fswatchsudo yum install fswatchsudo dnf install fswatchfswatch -r /path/to/directoryfswatch -0 /path/to/directory | while read -d '' event; do echo "Changed: $event"; doneauditd是Linux内核的审计系统,可详细记录文件访问、修改、删除等操作,适合安全审计和合规性检查。
sudo apt-get install auditd audispd-pluginssudo yum install auditecho "watch /path/to/directory -p wa -k my_dir_watch" | sudo tee -a /etc/audit/audit.rulessudo systemctl restart auditdausearch -k my_dir_watch轮询监控通过定时扫描文件状态(如修改时间、大小)来检测变化,无需内核支持,但实时性差、资源占用高。
watch -n 1 'ls -l /path/to/directory'#!/bin/bash
original_md5=$(md5sum /path/to/file)
while true; do
current_md5=$(md5sum /path/to/file)
if [ "$original_md5" != "$current_md5" ]; then
echo "File modified!"
original_md5=$current_md5
fi
sleep 5
done
watchdog是基于Python的文件系统监控库,支持实时监控和自定义事件处理,适合需要复杂逻辑的场景(如文件变化后触发数据处理)。
pip install watchdogimport time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"File modified: {event.src_path}")
def on_created(self, event):
print(f"File created: {event.src_path}")
def on_deleted(self, event):
print(f"File deleted: {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()
若需要监控整个文件系统的状态(如磁盘空间、inode使用率),可使用可视化工具,它们提供图形化界面和实时数据展示。
glances。http://localhost:19999查看。