-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor.py
More file actions
74 lines (62 loc) · 2.23 KB
/
Copy pathmonitor.py
File metadata and controls
74 lines (62 loc) · 2.23 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import logging
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import psutil
# Configure logging
logging.basicConfig(filename='monitor.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class MonitorHandler(FileSystemEventHandler):
def on_modified(self, event):
logging.info(f'File modified: {event.src_path}')
# Add more specific logic if needed
def on_created(self, event):
logging.info(f'File created: {event.src_path}')
# Add more specific logic if needed
def on_deleted(self, event):
logging.info(f'File deleted: {event.src_path}')
# Add more specific logic if needed
def monitor_files(path):
event_handler = MonitorHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
logging.info(f'Started monitoring {path}')
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
def monitor_network():
logging.info('Starting network activity monitoring...')
while True:
connections = psutil.net_connections()
for conn in connections:
if conn.status == 'ESTABLISHED':
logging.info(f'Established connection from {conn.laddr} to {conn.raddr}')
time.sleep(5)
def monitor_processes():
logging.info('Starting process activity monitoring...')
existing_pids = psutil.pids()
while True:
current_pids = psutil.pids()
new_pids = set(current_pids) - set(existing_pids)
for pid in new_pids:
try:
process = psutil.Process(pid)
logging.info(f'New process created: {process.name()} (PID: {pid})')
except psutil.NoSuchProcess:
pass
existing_pids = current_pids
time.sleep(5)
def main():
# Read configuration from a file or environment variables if needed
path_to_monitor = os.getenv('MONITOR_PATH', '.')
# Start monitoring
logging.info('Starting the monitoring system...')
monitor_files(path_to_monitor)
monitor_network()
monitor_processes()
if __name__ == '__main__':
main()