CentOS 6
Sponsored Link

Monitor files by inotify
2011/07/11
 
Monitor adding/updating/removing files by inotify.
[1] Install inotify tools.
[root@dlp ~]#
yum --enablerepo=epel -y install inotify-tools
 
# install from EPEL
[2] Try to use inotify.
[root@dlp ~]#
inotifywait -e create,delete,modify,move -mrq /etc &

[1] 3817
# try to create a file under the /etc

[root@dlp ~]#
touch /etc/test.txt

/etc/ CREATE test.txt
# detected
# try to rename the file

[root@dlp ~]#
mv /etc/test.txt /etc/test.conf

/etc/ MOVED_FROM test.txt
/etc/ MOVED_TO test.conf
# detected
# try to remove the file

[root@dlp ~]#
rm -f /etc/test.conf

/etc/ DELETE test.conf
# detected
[3] Create a init script.
[root@dlp ~]#
vi /etc/inotifywait.conf
# create config file
# specify log file

LOGFILE=/var/log/inotify.log
# specify target directory for monitoring

MONITOR=/etc
# specify target events for monitoring ( comma separated )

# refer ro "man inotifywait" for kinds of events

EVENT=create,delete,modify,move
[root@dlp ~]#
vi /etc/rc.d/init.d/inotifywait
# create init script
#!/bin/bash

# inotifywait: Start/Stop inotifywait
#
# chkconfig: - 80 20
# description: inotifywait waits for changes to files using inotify.
#
# processname: inotifywait

. /etc/rc.d/init.d/functions
. /etc/sysconfig/network
. /etc/inotifywait.conf

LOCK=/var/lock/subsys/inotifywait

RETVAL=0
start() {
   echo -n $"Starting inotifywait: "
   /usr/bin/inotifywait \
   --format '%w%f %e %T' \
   --timefmt '%Y/%m/%d-%H:%M:%S' \
   --exclude '.*\.sw[pox].*' \
   -e $EVENT \
   -o $LOGFILE \
   -dmrq $MONITOR

   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && touch $LOCK
   return $RETVAL
}
stop() {
   echo -n $"Stopping inotifywait: "
   killproc inotifywait
   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && rm -f $LOCK
   return $RETVAL
}
case "$1" in
   start)
      start
      ;;
   stop)
      stop
      ;;
   status)
      status inotifywait
      ;;
   restart)
      stop
      start
      ;;
   *)
      echo $"Usage: $0 {start|stop|status|restart}"
      exit 1
esac
exit $?

[root@dlp ~]#
chmod 755 /etc/rc.d/init.d/inotifywait

[root@dlp ~]#
/etc/rc.d/init.d/inotifywait start

Starting inotifywait:
[root@dlp ~]#
chkconfig --add inotifywait

[root@dlp ~]#
chkconfig inotifywait on
# try to do some actions

[root@dlp ~]#
touch /etc/test.txt

[root@dlp ~]#
mv /etc/test.txt /etc/test.conf

[root@dlp ~]#
vi /etc/test.conf
# edit something

[root@dlp ~]#
rm -f /etc/test.conf
# logs are taken like follows

[root@dlp ~]#
cat /var/log/inotify.log

/etc/test.txt MOVED_FROM 2011/07/11-19:13:06
/etc/test.conf MOVED_TO 2011/07/11-19:13:06
/etc/4913 CREATE 2011/07/11-19:13:25
/etc/4913 DELETE 2011/07/11-19:13:25
/etc/test.conf MOVED_FROM 2011/07/11-19:13:25
/etc/test.conf~ MOVED_TO 2011/07/11-19:13:25
/etc/test.conf CREATE 2011/07/11-19:13:25
/etc/test.conf MODIFY 2011/07/11-19:13:25
/etc/test.conf~ DELETE 2011/07/11-19:13:25
/etc/test.conf DELETE 2011/07/11-19:13:31
Matched Content
 
Tweet