inotify监测linux文件变化

系统版本:CentOS 7 1804 x64 inotify版本: 3.14 编辑安装需要gcc,可以提前通过yum install -y gcc安装

下载inotify地址:https://github.com/rvoicilas/inotify-tools/releases

tar -zxf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure --prefix=/usr/local/inotify-3.14
make && make install
ln -s /usr/local/inotify-3.14/bin/inotifywait /usr/bin
ln -s /usr/local/inotify-3.14/bin/inotifywatch /usr/bin

参数说明

inotifywait 参数说明

参数名称
参数说明

-m,–monitor

始终保持事件监听状态

-r,–recursive

递归查询目录

-q,–quiet

只打印监控事件的信息

–excludei

排除文件或目录时,不区分大小写

-t,–timeout

超时时间

–timefmt

指定时间输出格式 '%d/%m/%y %H:%M'

–format

指定时间输出格式 '%Xe %w%f' '%T %Xe %w%f'

-e,–event

后面指定删、增、改等事件

inotifywait events事件说明

事件名称
事件说明

access

读取文件或目录内容

modify

修改文件或目录内容

attrib

文件或目录的属性改变

close_write

修改真实文件内容

close_nowrite

close

open

文件或目录被打开

moved_to

文件或目录移动到

moved_from

文件或目录从移动

move

移动文件或目录移动到监视目录

create

在监视目录下创建文件或目录

delete

删除监视目录下的文件或目录

delete_self

unmount

卸载文件系统

以下每行一个示例,监控/data/目录下的文件变化,按设置的格式打印出相应的文件

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%Xe %w%f' -e modify,create,delete,attrib,close_write,move /data/ | while read file; do echo $date $time $dir $file ; done

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%Xe %w%f' -e modify,create,delete,attrib,close_write,move /data/ | while read date time dir file; do echo $date $time $dir $file ; done

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,create,delete,attrib,close_write,move /data/ | while read date time dir file; do echo $date $time $dir $file ; done

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %Xe %w%f' -e modify,create,delete,attrib,close_write,move /data/ | while read date time dir file; do echo $date $time $dir $file ; done

优化 Inotify

在/proc/sys/fs/inotify目录下有三个文件,对inotify机制有一定的限制

ls /proc/sys/fs/inotify/
max_queued_events max_user_instances max_user_watches

max_user_watches # 设置inotifywait或inotifywatch命令可以监视的文件数量(单进程) max_user_instances # 设置每个用户可以运行的inotifywait或inotifywatch命令的进程数 max_queued_events # 设置inotify实例事件(event)队列可容纳的事件数量

大部分情况下max_user_watches这个文件的默认值偏小,如果监控目录下文件数量过多会报如下错误

Failed to watch ./; upper limit on inotify watches reached!
Please increase the amount of inotify watches allowed per user via `/proc/sys/fs/inotify/max_user_watches'.

修改max_user_watches文件的值即可

cat /proc/sys/fs/inotify/max_user_watches	# 查看系统当前的值
8192
echo 8192000 > /proc/sys/fs/inotify/max_user_watches # 修改为8192000 可以把该 命令写入/etc/rc.local文件中,开机自动修改

示例脚本,如果监控目录文件发生了变化,就打印出发生变更的目录

inotifywait -mrq --format '%Xe %w%f' -e modify,create,delete,attrib,close_write,move /data/ | while read file; 
do 
INO_EVENT=$(echo $file | awk '{print $1}')      # 过滤出事件信息
NEW_PATH=$(echo $file | awk '{print $2}' | xargs dirname)   # 过滤出发生变更的文件目录
if [ $INO_EVENT == 'CREATE' ];      # 如果事件类型为 CREATE ,就打印出发生变更的文件目录
then
	echo $NEW_PATH
fi
done

最后更新于