温馨提示×

centos inotify如何编写使用教程

小樊
35
2025-10-26 07:06:53
栏目: 智能运维

CentOS inotify使用教程

一、inotify简介

inotify是Linux内核提供的文件系统事件监控机制,支持实时监控文件的创建、删除、修改、移动等操作,广泛应用于日志分析、备份同步、自动化部署等场景。CentOS系统可通过inotify-tools工具集便捷使用inotify功能。

二、安装inotify-tools

1. 准备工作

确保系统已安装epel-release源(可选,但推荐):

sudo yum install epel-release -y

2. 安装inotify-tools

通过yum直接安装(默认源已包含):

sudo yum install inotify-tools -y

安装完成后,可通过inotifywait --version验证是否成功。

三、基本使用命令

1. 监控单个文件

实时监控指定文件的修改、属性变化等事件(如/path/to/file.log):

inotifywait -m /path/to/file -e modify,attrib,close_write
  • -m:持续监控(不退出);
  • -e:指定监控的事件类型(可多个,用逗号分隔)。

2. 监控目录

递归监控目录及其子目录的所有变化(如/path/to/dir):

inotifywait -m -r /path/to/dir -e create,delete,modify,move
  • -r:递归监控子目录。

3. 输出自定义格式

通过--format--timefmt自定义输出内容(如添加时间戳、文件路径):

inotifywait -mr /path/to/dir --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S'
  • %T:时间(需配合--timefmt使用);
  • %w:监控路径;
  • %f:文件名;
  • %e:事件类型。

4. 监控多个目标

同时监控多个文件或目录(如/path/to/file1/path/to/dir):

inotifywait -m -e modify /path/to/file1 /path/to/dir

四、高级配置(调整内核参数)

inotify默认参数可能无法满足大规模监控需求,需调整以下内核参数:

1. 查看当前参数

sysctl -a | grep fs.inotify

关键参数说明:

  • fs.inotify.max_user_watches:单个用户可监控的文件/目录数量(默认约8192);
  • fs.inotify.max_user_instances:单个用户可创建的inotify实例数(默认128);
  • fs.inotify.max_queued_events:事件队列最大长度(默认16384)。

2. 临时修改参数(重启失效)

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

3. 永久修改参数

编辑/etc/sysctl.conf文件,添加以下内容:

fs.inotify.max_user_watches=524288
fs.inotify.max_user_instances=1024
fs.inotify.max_queued_events=4096

应用配置:

sudo sysctl -p

五、实战脚本示例

1. 文件变化日志记录

将监控目录的变化记录到日志文件(如/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

2. 实时同步文件(结合rsync)

监控源目录变化,自动同步到目标目录(如/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

六、注意事项

1. 内核支持检查

确保系统内核版本≥2.6.13(CentOS 5及以上均满足),可通过uname -a查看内核版本。

2. 性能优化

  • 避免监控过多小文件(如超过10万个文件可能导致性能下降);
  • 排除无需监控的目录(如/path/to/dir/cache/),可通过--exclude参数实现。

3. 开机自启

将监控脚本添加到/etc/rc.d/rc.local文件末尾(需赋予执行权限):

echo "/path/to/monitor.sh &" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local

通过以上步骤,可在CentOS系统中快速上手inotify监控,满足实时文件管理需求。

0