Linux文件监控工具——inotify-tools

举例:

ip.txt内容如下:

10.1.1.11 root 123
10.1.1.22 root 111
10.1.1.33 root 123456
10.1.1.44 root 54321
 

写法1:

cat ip.txt | while read ip user pass
do
    echo "$ip--$user--$pass"
done

 

 我的常用

inotifywait -mr --timefmt "%Y/%m/%d %H:%M:%S" --exclude "(.swp|.inc|.svn|.rar|.tar.gz|.gz|.log|.zip|.bak)" --format "%w %f %T"  -e create /var/www

/var/www/test/ lal.php 2020/07/26 17:07:54
/var/www/test/ test1.php 2020/07/26 17:08:32


inotifywait -mrq --timefmt "%Y/%m/%d %H:%M:%S" --exclude "(.swp|.inc|.svn|.rar|.tar.gz|.gz|.log|.zip|.bak)" --format "%w %f %T" -e create /var/www |while read dir file time
do
echo "$dir ---- $file ----$time"
done;


/var/www/test/ ---- 99111.php ----2020/07/26 17:11:01
/var/www/test/ ---- lucky.qphp ----2020/07/26 17:11:17

# 新建的文件移动到一个目录(防止未知的后门程序)

inotifywait -mrq --timefmt "%Y/%m/%d %H:%M:%S" --exclude "(.swp|.inc|.svn|.rar|.tar.gz|.gz|.log|.zip|.bak|^/www/wwwroot/project/vendor/*|^/www/wwwroot/project/storage/*)" --format "%w %f %T" -e create /www/wwwroot/project-dir |while read dir file time
do
echo "$dir---$file---$time" >> /home/hack/create.log
mv $dir$file /home/hack
done;

(这里不能加 -o ,使用 screen 后台程序)

 

# 后台运行监控文件变化
inotifywait -mrqd --timefmt "%Y/%m/%d %H:%M:%S" --exclude "(.swp|.inc|.svn|.rar|.tar.gz|.gz|.log|.zip|.bak)" --format "%e %w %f %T" -e create,modify,delete,attrib -o '/home/hack.log' /var/www


#!/bin/bash
 
DESTHOST=172.16.100.6
DESTHOSTDIR=/www/htdocs/
SRCDIR=/www/htdocs/
 
inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f'  
-e create,delete,modify,attrib $SRCDIR | while read DATE TIME DIR FILE; do
 $FILECHANGE=${DIR}${FILE}
 
 rsync -avze 'ssh' $SRCDIR root@${DESTHOST}:${DESTHOSTDIR} &>/dev/null && 
      echo "At ${TIME} on ${DATE}, file $FILECHANGE was backed up via rsync" >> /var/log/filesync.log
 
done

* inotifywait后面的--format '%e %w%f %T',决定了:while read能取到什么值。也就是主程序体中,能用到什么变量。 

* 常见组合inotifywait -rmq

% H 小时(00..23% I 小时(01..12% k 小时(0..23% l 小时(1..12% M 分(00..59% p 显示出AM或PM 
% r 时间(hh:mm:ss AM或PM),12小时 
% s 从1970年1月1日00:00:00到目前经历的秒数 
% S 秒(00..59% T 时间(24小时制)(hh:mm:ss) 
% X 显示时间的格式(%H:%M:%S) 
% Z 时区 日期域 
% a 星期几的简称( Sun..Sat) 
% A 星期几的全称( Sunday..Saturday) 
% b 月的简称(Jan..Dec) 
% B 月的全称(January..December) 
% c 日期和时间( Mon Nov 8 141246 CST 1999% d 一个月的第几天(01..31% D 日期(mm/dd/yy) 
% h 和%b选项相同 
% j 一年的第几天(001..366% m 月(01..12% w 一个星期的第几天(0代表星期天) 
% W 一年的第几个星期(00..53,星期一为第一天) 
% x 显示日期的格式(mm/dd/yy) 
% y 年的最后两个数字( 1999则是99) 
% Y 年(例如:1970,1996等) 

其他:

安装:https://github.com/inotify-tools/inotify-tools/wiki#getting

 https://www.cnblogs.com/caidingyu/p/11708851.html

https://blog.csdn.net/ab601026460/article/details/97380081

https://blog.csdn.net/huey2672/article/details/41895341

https://www.cnblogs.com/luoine/articles/4332380.html (rsync和notify 备份文件)

原文地址:https://www.cnblogs.com/boundless-sky/p/13379545.html