Scientific Linux 6
Sponsored Link

Monitor files by inotify2011/05/07

  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] 1227

# 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/rc.d/init.d/inotifywait


#!/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

LOCK=/var/lock/subsys/inotifywait
LOGFILE=/var/log/inotify.log
MONITOR=/etc

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 create,delete,modify,move \
   -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 CREATE 2011/05/08-00:53:31
/etc/test.txt MOVED_FROM 2011/05/08-00:53:42
/etc/test.conf MOVED_TO 2011/05/08-00:53:42
/etc/4913 CREATE 2011/05/08-00:53:53
/etc/4913 DELETE 2011/05/08-00:53:53
/etc/test.conf MOVED_FROM 2011/05/08-00:53:53
/etc/test.conf~ MOVED_TO 2011/05/08-00:53:53
/etc/test.conf CREATE 2011/05/08-00:53:53
/etc/test.conf MODIFY 2011/05/08-00:53:53
/etc/test.conf~ DELETE 2011/05/08-00:53:53
/etc/test.conf DELETE 2011/05/08-00:53:59
Matched Content