Linux

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > Linux > Linux inotify-tools监控目录变化

Linux使用inotify-tools监控目录变化的流程步骤

作者:鸠摩智首席音效师

Inotify 是一个Linux内核的特性,可以监控文件系统的变动情况,并做出通知响应,本文给大家详细介绍了Linux使用inotify-tools监控目录变化的流程步骤,需要的朋友可以参考下

当 Linux 系统目录中有新文件创建时执行命令,可以通过组合使用工具和脚本实现监控。一种常见的方法是使用 inotify-tools,这是一个允许您监视文件系统事件的实用程序,与 shell 脚本一起使用。

Step 1: 安装 inotify-tools

首先,你需要安装 inotify-tools,通常可以使用包管理器安装它。

sudo apt update 
sudo apt install inotify-tools

Step 2: 创建 Shell Script

接下来,创建一个 shell 脚本,该脚本使用 inotifywait 来监视目录中是否有新文件,然后在检测到新文件时调用 API,下面是这个脚本的简单示例:

#!/bin/bash

# Directory to monitor
MONITOR_DIR="/path/to/your/directory"

# Your custom command
# CUSTOM_COMMAND="curl -X POST -d @newfile http://your.api.endpoint"

# Monitor for new files and call the API
inotifywait -m -e create --format '%w%f' "$MONITOR_DIR" | while read NEWFILE
do
    echo "New file detected: $NEWFILE"
    # Uncomment to execute custom command
    #eval $CUSTOM_COMMAND
done

在此脚本中,将 “/path/to/your/directory” 替换为你想监控的目录,将“http://your.api.endpoint”替换为你的上传 API 地址,您也可以修改 CUSTOM_COMMAND 包括其它数据或参数选项。

Step 3: 执行脚本

修改文件权限,让其可以执行

chmod +x monitor.sh

执行脚本

bash monitor.sh

Step 4: 后台执行脚本

如果您希望这个脚本在后台连续运行,您可以使用 nohuptmux 会话中运行它。

For example:

nohup ./monitor.sh &

Step 5: 以 Systemd 服务方式运行脚本

确保您的脚本已正确编写和测试。将其放在合适的目录,例如: /usr/local/bin/

sudo mv monitor.sh /usr/local/bin/

确保它是可执行的

sudo chmod +x /usr/local/bin/monitor.sh

创建一个新的 systemd 服务文件

sudo nano /etc/systemd/system/monitor.service

将以下内容添加到文件中

[Unit]
Description=File Monitor Service

[Service]
ExecStart=/usr/local/bin/monitor.sh
Restart=always
User=nobody
Group=nogroup

[Install]
WantedBy=multi-user.target

保存并关闭该文件,重新加载 systemd 管理器配置

sudo systemctl daemon-reload

设置开机启动

sudo systemctl enable monitor.service

启动服务

sudo systemctl start monitor.service

检查服务状态

sudo systemctl status monitor.service

补充说明

到此这篇关于Linux使用inotify-tools监控目录变化的流程步骤的文章就介绍到这了,更多相关Linux inotify-tools监控目录变化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文