-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_monitor.py
More file actions
50 lines (38 loc) · 1.85 KB
/
Copy pathprocess_monitor.py
File metadata and controls
50 lines (38 loc) · 1.85 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
import psutil
import time
from datetime import datetime
# The "Forbidden" or "Monitored" apps we are looking for
# We use lowercase names to make matching easier
FORBIDDEN_APPS = ["notepad.exe", "calc.exe", "cmd.exe"]
LOG_FILE = "process_security.log"
def log_alert(app_name, pid):
"""Logs when a forbidden process is detected."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a") as f:
f.write(f"[{timestamp}] SECURITY ALERT: Forbidden App '{app_name}' (PID: {pid}) detected!\n")
def monitor_processes():
print(f"--- Process Surveillance Started ---")
print(f"--- Watching for: {', '.join(FORBIDDEN_APPS)} ---")
# We keep track of PIDs we've already alerted on so we don't spam the log
already_alerted = set()
try:
while True:
# Iterate over all running processes
for proc in psutil.process_iter(['pid', 'name']):
try:
name = proc.info['name'].lower()
pid = proc.info['pid']
if name in FORBIDDEN_APPS and pid not in already_alerted:
print(f"\n[!] ALERT: Forbidden application detected: {name} (PID: {pid})")
log_alert(name, pid)
already_alerted.add(pid)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
# Clean up PIDs of processes that have closed
current_pids = {p.pid for p in psutil.process_iter()}
already_alerted = already_alerted.intersection(current_pids)
time.sleep(2) # Check every 2 seconds
except KeyboardInterrupt:
print("\nProcess monitoring stopped.")
if __name__ == "__main__":
monitor_processes()