-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_monitor.py
More file actions
49 lines (39 loc) · 1.56 KB
/
Copy pathfile_monitor.py
File metadata and controls
49 lines (39 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime
# The folder we are surveilling ('.' means the current folder)
WATCH_DIRECTORY = "."
class SurveillanceHandler(FileSystemEventHandler):
"""Logs any file system event with a timestamp."""
def log_event(self, event_type, path):
timestamp = datetime.now().strftime("%H:%M:%S")
# We ignore our own log files and folders starting with '.' (like .git or .idea)
if not os.path.basename(path).startswith('.') and "log" not in path:
print(f"[{timestamp}] ALERT: File {event_type} -> {path}")
def on_created(self, event):
if not event.is_directory:
self.log_event("CREATED", event.src_path)
def on_modified(self, event):
if not event.is_directory:
self.log_event("MODIFIED", event.src_path)
def on_deleted(self, event):
if not event.is_directory:
self.log_event("DELETED", event.src_path)
def run_surveillance():
event_handler = SurveillanceHandler()
observer = Observer()
observer.schedule(event_handler, WATCH_DIRECTORY, recursive=False)
print(f"--- File System Surveillance Started ---")
print(f"--- Watching directory: {os.path.abspath(WATCH_DIRECTORY)} ---")
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("\nSurveillance stopped.")
observer.join()
if __name__ == "__main__":
run_surveillance()