inotify是Linux内核提供的文件系统事件监控机制,支持实时监控文件的创建、删除、修改、移动等操作,广泛应用于日志分析、备份同步、自动化部署等场景。CentOS系统可通过inotify-tools工具集便捷使用inotify功能。
确保系统已安装epel-release源(可选,但推荐):
sudo yum install epel-release -y
通过yum直接安装(默认源已包含):
sudo yum install inotify-tools -y
安装完成后,可通过inotifywait --version验证是否成功。
实时监控指定文件的修改、属性变化等事件(如/path/to/file.log):
inotifywait -m /path/to/file -e modify,attrib,close_write
-m:持续监控(不退出);-e:指定监控的事件类型(可多个,用逗号分隔)。递归监控目录及其子目录的所有变化(如/path/to/dir):
inotifywait -m -r /path/to/dir -e create,delete,modify,move
-r:递归监控子目录。通过--format和--timefmt自定义输出内容(如添加时间戳、文件路径):
inotifywait -mr /path/to/dir --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S'
%T:时间(需配合--timefmt使用);%w:监控路径;%f:文件名;%e:事件类型。同时监控多个文件或目录(如/path/to/file1和/path/to/dir):
inotifywait -m -e modify /path/to/file1 /path/to/dir
inotify默认参数可能无法满足大规模监控需求,需调整以下内核参数:
sysctl -a | grep fs.inotify
关键参数说明:
fs.inotify.max_user_watches:单个用户可监控的文件/目录数量(默认约8192);fs.inotify.max_user_instances:单个用户可创建的inotify实例数(默认128);fs.inotify.max_queued_events:事件队列最大长度(默认16384)。sudo sysctl -w fs.inotify.max_user_watches=524288
sudo sysctl -w fs.inotify.max_user_instances=1024
sudo sysctl -w fs.inotify.max_queued_events=4096
编辑/etc/sysctl.conf文件,添加以下内容:
fs.inotify.max_user_watches=524288
fs.inotify.max_user_instances=1024
fs.inotify.max_queued_events=4096
应用配置:
sudo sysctl -p
将监控目录的变化记录到日志文件(如/var/log/inotify.log):
#!/bin/bash
MONITOR_DIR="/path/to/monitor"
LOG_FILE="/var/log/inotify.log"
# 清空日志文件
> $LOG_FILE
# 持续监控并追加日志
inotifywait -mr "$MONITOR_DIR" --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' >> "$LOG_FILE" 2>&1 &
echo "inotify监控已启动,日志路径:$LOG_FILE"
赋予执行权限并运行:
chmod +x monitor.sh
./monitor.sh
监控源目录变化,自动同步到目标目录(如/source同步到/backup):
#!/bin/bash
SOURCE_DIR="/path/to/source"
DEST_DIR="/path/to/backup"
LOG_FILE="/var/log/inotify_sync.log"
inotifywait -mr -e create,modify,delete "$SOURCE_DIR" | while read path action file; do
echo "$(date '+%Y-%m-%d %H:%M:%S') - $path$file 发生 $action 事件" >> "$LOG_FILE"
rsync -avz --delete "$SOURCE_DIR/" "$DEST_DIR/" >> "$LOG_FILE" 2>&1
done
赋予执行权限并运行:
chmod +x sync_script.sh
./sync_script.sh
确保系统内核版本≥2.6.13(CentOS 5及以上均满足),可通过uname -a查看内核版本。
/path/to/dir/cache/),可通过--exclude参数实现。将监控脚本添加到/etc/rc.d/rc.local文件末尾(需赋予执行权限):
echo "/path/to/monitor.sh &" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
通过以上步骤,可在CentOS系统中快速上手inotify监控,满足实时文件管理需求。