什么是INOTIFY-TOOLS?
Inotify-tools是一个与inotify内核功能接口的C库。Inotify-tools在2.6.13之后的内核上可用。这些工具可以监视或基于文件系统事件采取行动,这对于脚本化事件发生时您希望执行的动作特别有用。
在FEDORA / CENTOS / REDHAT上安装:
安装epel仓库:
yum install epel-release
安装inotify工具:
yum install inotify-tools
在DEBIAN / UBUNTU上安装:
apt-get install inotify-tools
安装后,您可以访问inotifywait
Inotifywait可以监视inotify事件,它可以监视特定的目录,目录或递归目录树。默认情况下,inotifywait检查所有事件到受监视的文件或目录
Inotify语法是:
inotify filename
实例化:
[root@server ~]$ inotifywait /test
Setting up watches.
Watches established.
/tmp/ MODIFY test
您可以关注的INOTIFYWAIT事件列表:
access –已准备好要监视的文件。
modify–正在监视的文件已写入。
attrib –更改了受监视文件的属性(时间戳,文件许可权,属性)
close_write –处于可写状态后,正在监视的文件已关闭
close –正在监视的文件已关闭
open–已打开受监视的文件
move_to –将文件移到受监视的目录
move_from –将文件或目录移至
delete –将被监视目录中的文件或目录删除
delete_self –删除了受监视的文件或目录,此后将不再监视该文件和目录。
umount –已卸载文件系统,表明受监视的文件/文件夹已打开。
INOTIFYWAIT的完整示例:
## script to detect new files
WATCHDIR='/src/';
OUTDIR='/dst/';
inotifywait -m -q -e close_write --format %f ${WATCHDIR} | while IFS= read -r file; do
cp -p ${WATCHDIR}/"$file" ${OUTDIR}/
done
-m代表监视器(默认情况下inotifywait将在第一个事件后关闭)
-r表示递归
这样的脚本也可以放在/etc/rc.local中以在启动时启动。
inotifywait调用rsync示例:
#!/bin/bash
# Supposed to run on rsync-host01, change rsync-host02 to rsync-host01 to make a script that is meant to run on rsync-host02.
while true; do
inotifywait -r -e modify,attrib,close_write,move,create,delete /opt/syncfiles
rsync -avz -e "ssh -i /root/rsync-key -o StrictHostKeyChecking=no“ /opt/syncfiles/ root@rsync-host02:/opt/syncfiles/
done