-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsys_monitor.py
More file actions
54 lines (43 loc) · 1.85 KB
/
Copy pathsys_monitor.py
File metadata and controls
54 lines (43 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
51
52
53
54
import psutil
import time
import os
from datetime import datetime
# Log file name
LOG_FILE = "monitor_alerts.log"
def clear_screen():
# Clears the terminal screen (works for Windows/Mac/Linux)
os.system('cls' if os.name == 'nt' else 'clear')
def log_alert(message):
"""Writes a message with a timestamp to the log file."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a") as f:
f.write(f"[{timestamp}] {message}\n")
def run_monitor():
print(f"--- System Surveillance Started (Ctrl+C to stop) ---")
print(f"--- Logging alerts to: {LOG_FILE} ---")
try:
while True:
# 1. Get CPU usage (interval=1 means it averages over 1 second)
cpu_usage = psutil.cpu_percent(interval=1)
# 2. Get RAM usage
memory = psutil.virtual_memory()
# 3. Get Disk usage
disk = psutil.disk_usage('/')
clear_screen()
print(f"--- REAL-TIME SYSTEM MONITOR ---")
print(f"CPU Usage: [{'#' * int(cpu_usage/5)}{' ' * (20-int(cpu_usage/5))}] {cpu_usage}%")
print(f"RAM Usage: {memory.percent}% ({memory.used // (1024**2)}MB / {memory.total // (1024**2)}MB)")
print(f"Disk Space: {disk.percent}% used")
# SURVEILLANCE LOGIC: Log alerts for high usage
if cpu_usage > 80:
msg = f"CRITICAL: High CPU usage detected: {cpu_usage}%"
print(f"\n[!] {msg}")
log_alert(msg)
if memory.percent > 90:
msg = f"CRITICAL: High RAM usage detected: {memory.percent}%"
print(f"\n[!] {msg}")
log_alert(msg)
except KeyboardInterrupt:
print("\nMonitoring stopped by user.")
if __name__ == "__main__":
run_monitor()