博客 (2)

本文适用于 Window,CentOS(Linux) 系统请移步:http://xoyozo.net/Blog/Details/inotify-tools


FileSystemWatcher

关于监视文件系统事件的介绍

https://docs.microsoft.com/zh-cn/previous-versions/visualstudio/visual-studio-2008/ch2s8yd7(v=vs.90)


以控制台应用程序为例:

using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void Run()
    {
        string[] args = Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = args[1];

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            // Only watch text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e) =>
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");

    private static void OnRenamed(object source, RenamedEventArgs e) =>
        // Specify what is done when a file is renamed.
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}


xoyozo 4 年前
3,236

本文适用于 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 年前
3,641