今天介绍的是利用Linux内核的特性inotify来实时监控服务器上的文件,任何文件发生变化的时候,记录到日志中保存起来。国际惯例,先介绍实验环境

环境

服务器系统:CentOS

文件目录:/home/testing

目的

当/home/testing下面除了data目录之外,任何文件发生变化时,记录日志并保存。

步骤

1、查看内核是否支持inotify

#列出文件目录,出现下面的内容则表示内核支持inotify

ll /proc/sys/fs/inotify

-rw-r--r-- 1 root root 0 5月  29 08:21 max_queued_events

-rw-r--r-- 1 root root 0 5月  29 08:21 max_user_instances

-rw-r--r-- 1 root root 0 5月  29 08:21 max_user_watches

注意:支持inotify的内核版本最小为2.6.13,可以用uname -a查看内核

2、安装inotify-tools

#安装编译工具,已安装过的忽略

yum install make gcc gcc-c++

#inotify-tools的github地址https://github.com/rvoicilas/inotify-tools/

#直接用weget下载或者本机下载好后再上传到你习惯的目录

#然后进行解压并进入解压目录进行配置,最后编译

cd /usr/local/src

unzip inotify-tools-master.zip && cd inotify-tools-master

./configure --prefix=/usr/local/inotify && echo OK

make && make install && echo OK

3、设置环境变量,添加软连接

echo "PATH=/usr/local/inotify/bin:$PATH" >>/etc/profile.d/inotify.sh

#使设置立即生效

source /etc/profile.d/inotify.sh

echo "/usr/local/inotify/lib" >/etc/ld.so.conf.d/inotify.conf

ln -s /usr/local/inotify/include /usr/include/inotify

4、修改inotify的默认参数

#先查看一下默认参数

sysctl -a | grep max_queued_events

#结果为fs.inotify.max_queued_events = 16384

sysctl -a | grep max_user_watches

#结果为fs.inotify.max_user_watches = 8192

sysctl -a | grep max_user_instances

#结果为fs.inotify.max_user_instances = 128

#直接修改参数,并在/etc/sysctl.conf中添加代码

sysctl -w fs.inotify.max_queued_events="99999999"

sysctl -w fs.inotify.max_user_watches="99999999"

sysctl -w fs.inotify.max_user_instances="65535"

vim /etc/sysctl.conf

fs.inotify.max_queued_events=99999999

fs.inotify.max_user_watches=99999999

fs.inotify.max_user_instances=65535

:wq!

#参数说明

max_queued_events

inotify队列最大长度,如果值太小,会出现"** Event Queue Overflow **"错误,导致监控文件不准确

max_user_watches

要同步的文件包含多少目录,可以用:find /home/*** -type d | wc -l 统计,必须保证max_user_watches值大于统计结果(这里/home/***为同步文件目录)

max_user_instances

每个用户创建inotify实例最大值

5、创建实时监控脚本

mkdir -p /shell

#创建目录

vi /shell/inotif.sh

#编辑

#!/bin/sh

/usr/local/inotify/bin/inotifywait -mrq -e modify,create,move,delete --fromfile '/shell/excludedir' --timefmt '%y-%m-%d %H:%M' --format '%T %f %e'

/home/web/ >> /tmp/rsync.txt

:wq!

#保存退出

vim /shell/excludedir

#编辑

/home/web/data/

@/home/web/cache/

#排除的目录

:wq!

#保存退出

chmod +x /shell/inotif.sh

#添加执行权限

vi /etc/rc.d/rc.local

#编辑,在最后添加一行,开机自动执行

sh /shell/inotif.sh

:wq!

#保存退出

www.osgnu.com  温馨提醒:BruceZ原创内容 版权所有,转载请注明出处以及原文链接。

本文链接:www.osgnu.com/Inotify/2.html

转载请注明来源:OSGNU >> 利用inotify-tool实时监控服务器文件