Pregunta

I am using this code to detect when files/dirs are created in a folder. It works fine when new files/dirs are created in the specified folder. But it doesn't notify or log files/dirs when they are moved into the folder. How can I detect that?

#!/usr/bin/env python

# monitors both files and dirs

import os
import pyinotify
from datetime import datetime

timestamp = datetime.today()
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE

class PTmp(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Created: %s " % os.path.join(event.path, event.name)
        event_log = open('/home/saad/Code/test/event_log', 'a')
        event_log.write(event.name + ' - ' + timestamp.strftime('%c') + '\n')
        event_log.close()

notifier = pyinotify.Notifier(wm, PTmp())

wdd = wm.add_watch('/home/saad/Code/test/foo', mask, rec=True)

while True:
    try:
        notifier.process_events()
        if notifier.check_events():
            notifier.read_events()
    except KeyboardInterrupt:
        notifier.stop()
        break
¿Fue útil?

Solución

You can watch the IN_MOVED_TO event:

mask = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO

class PTmp(pyinotify.ProcessEvent):
    ...
    def process_IN_MOVED_TO(self, event):
        print "Moved: %s " % os.path.join(event.path, event.name)
        event_log = open('/home/saad/Code/test/event_log', 'a')
        event_log.write(event.name + ' - ' + timestamp.strftime('%c') + '\n')
        event_log.close()

(Not tested as I don't have a Linux box available right now).

A full list of inotify events is available in the man page or in the pyinotify doc.

Otros consejos

Use afick tool, for linux, from a CD driver, so afick can't be touched and it will alert you by email of any changes on your system... if it is a webserver, it's very recommended you create a CD or DVD and ask them to put it in a mounted CD DRIVE in your server. Else use it from outside but i don't know how that would be achieved.

http://archive09.linux.com/feature/113944

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top