Versión python
Estas son las pruebas con Pyinotify. Os tenéis que descargar el paquete primero.
He elaborado el tutorial a partir de aquí
http://pyinotify.sourceforge.net/
La creación de archivos la monitorea perfectamente, la eliminación siempre que se realice mediante el comando rm o shift+supr (es decir, se haga algo más que mover a la papelera).
Sin embargo, el cambio de atributos no me lo monitorea puesto que lo modifico y debería cambiar la fecha de última modificación. Además, me dice que han sido modificados archivos extraños cuando intento modificar un archivo desde el editor de texto.
Si le podéis echar un vistazo.
Recordad una vez más lo de la indentación.
Os pongo una versión con threads y otra sin threads.
Versión sin threads
Contenido de 'inotify-test.py'
#!/usr/bin/env python # encoding: utf-8 # Importa las librerías adecuada import os from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent # PON TU NOMBRE DE USUARIO DENTRO DEL HOME username = "salvador" # El objeto que monitorea wm = WatchManager() # Qué queremos monitorear mask = EventsCodes.IN_DELETE | EventsCodes.IN_CREATE | EventsCodes.IN_MODIFY | EventsCodes.IN_ATTRIB # Esto significa "PHome que hereda de ProcessEvent" class PHome(ProcessEvent): def process_IN_CREATE(self, event): print "Create: %s" % os.path.join(event.path, event.name) def process_IN_DELETE(self, event): print "Remove: %s" % os.path.join(event.path, event.name) def process_IN_MODIFY(self, event): print "Modify: %s" % os.path.join(event.path, event.name) def process_IN_ATTRIB(self, event): print "Attribute modified: %s" % os.path.join(event.path, event.name) # El notificador notifier = Notifier(wm, PHome()) # Esto asigna un "vigilante" al directorio /home/nombre-usuario indicando recursividad wdd = wm.add_watch('/home/' + username, mask, rec=False) # Bucle infinito, versión sin threads while True: try: # Procesa los eventos notifier.process_events() if notifier.check_events(): # Lee los eventos y los introduce en una cola notifier.read_events() # Aquí se puede añadir código # Interrupción por teclado except KeyboardInterrupt: # Para de monitorear notifier.stop() #Sale del bucle infinito break
Versión con threads
Contenido de 'inotify-threaded-test.py'
#!/usr/bin/env python # encoding: utf-8 # Importa las librerías adecuada import os from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent # PON TU NOMBRE DE USUARIO DENTRO DEL HOME username = "salvador" # El objeto que monitorea wm = WatchManager() # Qué queremos monitorear mask = EventsCodes.IN_DELETE | EventsCodes.IN_CREATE | EventsCodes.IN_MODIFY | EventsCodes.IN_ATTRIB # Esto significa "PHome que hereda de ProcessEvent" class PHome(ProcessEvent): def process_IN_CREATE(self, event): print "Create: %s" % os.path.join(event.path, event.name) def process_IN_DELETE(self, event): print "Remove: %s" % os.path.join(event.path, event.name) def process_IN_MODIFY(self, event): print "Modify: %s" % os.path.join(event.path, event.name) def process_IN_ATTRIB(self, event): print "Attribute modified: %s" % os.path.join(event.path, event.name) # El notificador, con threads notifier = ThreadedNotifier(wm, PHome()) notifier.start() # Comienza el thread # Esto asigna un "vigilante" al directorio /home/nombre-usuario indicando recursividad wdd = wm.add_watch('/home/' + username, mask, rec=False) # Bucle infinito, versión con threads while True: try: # Aquí se puede añadir código pass # Interrupción por teclado except KeyboardInterrupt: #Sale del bucle infinito break # Para de monitorear notifier.stop()
Versión C / C++, sin wrappers
// Initialize Inotify fd = inotify_init (); if (fd < 0) return -errno; // Add a Watch int wd; wd = inotify_add_watch (fd, filename, mask); if (wd < 0) return -errno; // Read an inotify event (buffer should be at least the size of static struc inotify_event *buffer = NULL; buffer_size = sizeof (struct inotify_event); *nr = read (fd, buffer, buffer_size); inotify_rm_watch(wd);
Y dejo el link de inotify-cxx, unas clases para trabajar con inotify en C++. Son sencillas y cortas, y además puedes editarlas o ampliarlas :)
http://inotify.aiken.cz/doc/inotify-cxx/html/annotated.html
Eventos que monitoriza inoitfy
Tabla 1. Eventos
Evento | Descripción |
---|---|
IN_ACCESS | File was read from |
IN_MODYFY | File was written to |
IN_ATTRIB | File's metadata (inode or xattr) was changed. |
IN_CLOSE_WRITE | File was closed (and was open for writing). |
IN_CLOSE_NO_WRITE | File was closed (and was not open for writing) |
IN_OPEN | File was opened |
IN_MOVED_FROM | File was moved away from watch. |
IN_MOVED_TO | File was moved to watch. |
IN_DELETE | File was deleted. |
IN_DELETE_SELF | The watch itself was deleted. |
Tabla 2. Eventos de ayuda
Evento | Descripción |
---|---|
IN_CLOSE | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE |
IN_MOVE | IN_MOVED_FROM | IN_MOVED_TO |
IN_ALL_EVENTS | Bitwise OR of all events. |