ubuntu

Ubuntu inotify如何检测文件移动

小樊
39
2025-11-17 01:02:08
栏目: 智能运维

在Ubuntu中,你可以使用inotify-tools来检测文件移动

  1. 首先,确保你已经安装了inotify-tools。如果没有,请运行以下命令来安装:
sudo apt-get update
sudo apt-get install inotify-tools
  1. 创建一个名为inotify_move_detector.sh的脚本文件,并在其中输入以下内容:
#!/bin/bash

# 检查参数数量
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <watch_directory> <output_file> <timeout>"
    exit 1
fi

# 设置变量
WATCH_DIR=$1
OUTPUT_FILE=$2
TIMEOUT=$3

# 使用inotifywait监视目录
inotifywait -m -r -e moved_to,moved_from --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' "${WATCH_DIR}" |
while read FILE EVENT; do
    echo "$(date +"%Y-%m-%d %H:%M:%S") - ${FILE} - ${EVENT}" >> "${OUTPUT_FILE}"
done &
PID=$!

# 等待超时或脚本被终止
wait $PID || kill $PID

exit 0
  1. 保存脚本文件并为其添加可执行权限:
chmod +x inotify_move_detector.sh
  1. 运行脚本,指定要监视的目录、输出文件和超时时间(以秒为单位)。例如,要监视/home/user/documents目录,并在output.log文件中记录事件,设置超时时间为60秒:
./inotify_move_detector.sh /home/user/documents output.log 60

脚本将监视指定的目录,并在检测到文件移动时将相关信息记录到输出文件中。当超时时间到达或脚本被终止时,脚本将自动停止监视。

注意:inotifywait可能会消耗大量系统资源,特别是在监视大型目录时。因此,请谨慎使用,并根据需要调整超时时间。

0
看了该问题的人还看了