用 inotify-tools 监视文件系统事件并对其采取行动

本文发布于 4 年前,部分内容可能已经失去参考价值。

本文适用于 CentOS(Linux),Window 系统请移步:https://xoyozo.net/Blog/Details/FileSystemWatcher


安装

参照官方说明:https://github.com/inotify-tools/inotify-tools/wiki

以 CentOS 为例:

安装 EPEL :

yum install -y epel-release && yum update

安装 inotify-tools:

yum install inotify-tools

在 CentOS-7 中

yum --enablerepo=epel install inotify-tools

v3.14-8.el7.×86_64 as of 4-18-2018


配置

创建 Shell 脚本文件:

#!/bin/bash
inotifywait -mrq -e modify,attrib,move,create,delete /要监视的目录 | while read dir event file;
do
  curl -d "df=${dir}${file}&ev=${event}" https://xxx.xxx.xxx/api/inotify/
done

并将该文件设置为可执行:chmod +x xxx.sh

注:上述示例将对文件的部分操作事件信息传递到远程接口。inotifywaitcurl 的用法请自行百度。


如果需要忽略部分文件路径,可以使用正则表达式进行过滤,例:

#!/bin/bash
inotifywait -mrq -e modify,attrib,move,create,delete /要监视的目录 | while read dir event file;
do
  df=${dir}${file};
  if [[ ! $df =~ ^/www/wwwroot/[0-9a-z]+.xxx.com/[0-9a-zA-Z]+/Runtime/Cache/[0-9a-zA-Z]+/[0-9a-f]{32}.php$
     && ! $df =~ ^/www/wwwroot/[0-9a-z]+.xxx.com/[0-9a-zA-Z]+/Runtime/Logs/[0-9a-zA-Z]+/[0-9]{2}_[0-9]{2}_[0-9]{2}.log$
    ]]; then
    curl -d "df=${df}&ev=${event}" https://xxx.xxx.xxx/api/inotify/
  else
    echo "Ignored: $df"
  fi
done

注意:bash 中使用 [[ string =~ regex ]] 表达式进行正则匹配,“!”取反,“&&”为且,书写时不要吝啬使用空格,否则程序可能不会按预期运行。


执行

先直接执行 sh 命令,排查一些错误。

Failed to watch /www/wwwroot; upper limit on inotify watches reached!

Please increase the amount of inotify watches allowed per user via `/proc/sys/fs/inotify/max_user_watches'.

因被监视的目录中文件数超过默认值 8192 提示失败,更改该值即可。

echo 8192000 > /proc/sys/fs/inotify/max_user_watches

设置开机自动运行,参:https://xoyozo.net/Blog/Details/linux-init-d


xoyozo 4 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容