Repository navigation
Expand file tree
/
Copy pathsystem_monitor.py
More file actions
373 lines (317 loc) · 13.5 KB
/
Copy pathsystem_monitor.py
File metadata and controls
373 lines (317 loc) · 13.5 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
"""
System Monitor & Info Tool
Per uso personale su dispositivi propri
Compatibile con Kali Linux e Termux
"""
import os
import sys
import platform
import socket
import subprocess
import json
import time
from datetime import datetime
class SystemMonitor:
def __init__(self):
self.is_termux = 'com.termux' in os.environ.get('PREFIX', '')
self.is_root = os.geteuid() == 0 if hasattr(os, 'geteuid') else False
self.monitoring = False
def banner(self):
print("\n" + "="*50)
print(" System Monitor & Info Tool")
print(" Per uso personale")
print("="*50 + "\n")
def get_system_info(self):
"""Raccoglie informazioni di sistema base"""
info = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"hostname": socket.gethostname(),
"platform": platform.system(),
"platform_release": platform.release(),
"platform_version": platform.version(),
"architecture": platform.machine(),
"processor": platform.processor(),
"is_termux": self.is_termux,
"is_root": self.is_root
}
return info
def get_network_info(self):
"""Raccoglie informazioni di rete"""
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
# Ottiene interfacce di rete
if self.is_termux:
cmd = "ip addr show"
else:
cmd = "ip addr show" if os.path.exists("/sbin/ip") else "ifconfig"
result = subprocess.run(cmd.split(), capture_output=True, text=True)
interfaces = result.stdout
return {
"hostname": hostname,
"local_ip": local_ip,
"interfaces": interfaces
}
except Exception as e:
return {"error": str(e)}
def get_process_info(self):
"""Lista processi in esecuzione"""
try:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_disk_info(self):
"""Informazioni sui dischi"""
try:
result = subprocess.run(['df', '-h'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_memory_info(self):
"""Informazioni sulla memoria"""
try:
result = subprocess.run(['free', '-h'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_users_info(self):
"""Utenti connessi"""
try:
result = subprocess.run(['who'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_cpu_info(self):
"""Informazioni dettagliate CPU"""
try:
cpu_info = {}
# Load average
result = subprocess.run(['uptime'], capture_output=True, text=True)
cpu_info['uptime'] = result.stdout.strip()
# CPU cores
result = subprocess.run(['nproc'], capture_output=True, text=True)
cpu_info['cores'] = result.stdout.strip()
# CPU usage via top
result = subprocess.run(['top', '-bn1'], capture_output=True, text=True)
cpu_info['top_info'] = result.stdout
return cpu_info
except Exception as e:
return {"error": str(e)}
def get_wireless_info(self):
"""Informazioni interfacce wireless"""
try:
result = subprocess.run(['iwconfig'], capture_output=True, text=True)
wireless_info = {"iwconfig": result.stdout}
# Aggiungi dettagli iw dev se disponibile
result = subprocess.run(['iw', 'dev'], capture_output=True, text=True)
wireless_info['iw_dev'] = result.stdout
return wireless_info
except Exception as e:
return {"error": str(e)}
def get_connections_info(self):
"""Connessioni di rete attive"""
try:
result = subprocess.run(['ss', '-tunap'], capture_output=True, text=True)
return result.stdout
except:
try:
result = subprocess.run(['netstat', '-tunap'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_services_info(self):
"""Servizi in esecuzione"""
try:
if os.path.exists('/usr/bin/systemctl'):
result = subprocess.run(['systemctl', 'list-units', '--type=service', '--state=running'],
capture_output=True, text=True)
return result.stdout
else:
return "systemctl non disponibile"
except Exception as e:
return f"Errore: {str(e)}"
def get_logged_events(self, lines=50):
"""Eventi recenti dal sistema"""
try:
result = subprocess.run(['tail', f'-n{lines}', '/var/log/auth.log'],
capture_output=True, text=True)
return result.stdout
except:
try:
result = subprocess.run(['dmesg'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def get_io_stats(self):
"""Statistiche I/O disco"""
try:
result = subprocess.run(['iostat', '-x', '1', '2'], capture_output=True, text=True)
return result.stdout
except:
try:
result = subprocess.run(['cat', '/proc/diskstats'], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Errore: {str(e)}"
def display_menu(self):
"""Menu interattivo"""
print("\n[1] Informazioni Sistema")
print("[2] Informazioni Rete")
print("[3] Processi Attivi")
print("[4] Utilizzo Dischi")
print("[5] Utilizzo Memoria")
print("[6] Utenti Connessi")
print("[7] Info CPU Dettagliate")
print("[8] Interfacce Wireless")
print("[9] Connessioni Attive (ss/netstat)")
print("[10] Servizi Attivi")
print("[11] Log Sistema")
print("[12] Statistiche I/O")
print("[13] Report Completo (JSON)")
print("[14] Report Completo (Testo)")
print("[15] Monitoring Real-Time")
print("[0] Esci\n")
def real_time_monitor(self):
"""Monitoring real-time sistema"""
self.monitoring = True
print("\n=== MONITORING REAL-TIME ===")
print("Premi CTRL+C per fermare\n")
try:
while self.monitoring:
os.system('clear')
print(f"\n{'='*60}")
print(f" System Monitor - {datetime.now().strftime('%H:%M:%S')}")
print(f"{'='*60}\n")
print("=== MEMORIA ===")
print(self.get_memory_info())
print("\n=== CPU (TOP 10) ===")
try:
result = subprocess.run(['ps', 'aux', '--sort=-%cpu', '|', 'head', '-n', '11'],
capture_output=True, text=True, shell=True)
print(result.stdout)
except:
print("Errore nel recupero CPU")
print("\n=== UTILIZZO DISCHI ===")
print(self.get_disk_info())
time.sleep(2)
except KeyboardInterrupt:
self.monitoring = False
print("\n\nMonitoring fermato.")
def generate_full_report(self, format='text'):
"""Genera report completo"""
print("\nGenerazione report in corso...\n")
report = {
"system_info": self.get_system_info(),
"network_info": self.get_network_info(),
"disk_info": self.get_disk_info(),
"memory_info": self.get_memory_info(),
"users_info": self.get_users_info(),
"cpu_info": self.get_cpu_info(),
"wireless_info": self.get_wireless_info(),
"connections": self.get_connections_info(),
"services": self.get_services_info()
}
if format == 'json':
return json.dumps(report, indent=2)
else:
text = "\n=== REPORT SISTEMA ===\n\n"
text += "--- Informazioni Sistema ---\n"
for k, v in report['system_info'].items():
text += f"{k}: {v}\n"
text += "\n--- Informazioni Rete ---\n"
text += str(report['network_info']) + "\n"
text += "\n--- Utilizzo Dischi ---\n"
text += report['disk_info'] + "\n"
text += "\n--- Utilizzo Memoria ---\n"
text += report['memory_info'] + "\n"
text += "\n--- Utenti Connessi ---\n"
text += report['users_info'] + "\n"
return text
def run(self):
"""Esegue il tool in modalità interattiva"""
self.banner()
while True:
self.display_menu()
try:
choice = input("Seleziona opzione: ").strip()
if choice == '1':
info = self.get_system_info()
print("\n=== INFORMAZIONI SISTEMA ===")
for key, value in info.items():
print(f"{key}: {value}")
elif choice == '2':
info = self.get_network_info()
print("\n=== INFORMAZIONI RETE ===")
for key, value in info.items():
print(f"\n{key}:")
print(value)
elif choice == '3':
print("\n=== PROCESSI ATTIVI ===")
print(self.get_process_info())
elif choice == '4':
print("\n=== UTILIZZO DISCHI ===")
print(self.get_disk_info())
elif choice == '5':
print("\n=== UTILIZZO MEMORIA ===")
print(self.get_memory_info())
elif choice == '6':
print("\n=== UTENTI CONNESSI ===")
print(self.get_users_info())
elif choice == '7':
print("\n=== INFO CPU DETTAGLIATE ===")
info = self.get_cpu_info()
for key, value in info.items():
print(f"\n{key.upper()}:")
print(value)
elif choice == '8':
print("\n=== INTERFACCE WIRELESS ===")
info = self.get_wireless_info()
for key, value in info.items():
print(f"\n--- {key} ---")
print(value)
elif choice == '9':
print("\n=== CONNESSIONI ATTIVE ===")
print(self.get_connections_info())
elif choice == '10':
print("\n=== SERVIZI ATTIVI ===")
print(self.get_services_info())
elif choice == '11':
print("\n=== LOG SISTEMA ===")
print(self.get_logged_events())
elif choice == '12':
print("\n=== STATISTICHE I/O ===")
print(self.get_io_stats())
elif choice == '13':
print("\n=== REPORT COMPLETO (JSON) ===")
report = self.generate_full_report('json')
print(report)
filename = f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, 'w') as f:
f.write(report)
print(f"\nReport salvato in: {filename}")
elif choice == '14':
print("\n=== REPORT COMPLETO ===")
report = self.generate_full_report('text')
print(report)
filename = f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(filename, 'w') as f:
f.write(report)
print(f"\nReport salvato in: {filename}")
elif choice == '15':
self.real_time_monitor()
elif choice == '0':
print("\nArrivederci!")
break
else:
print("\nOpzione non valida!")
input("\nPremi INVIO per continuare...")
except KeyboardInterrupt:
print("\n\nInterrotto dall'utente. Arrivederci!")
break
except Exception as e:
print(f"\nErrore: {str(e)}")
if __name__ == "__main__":
monitor = SystemMonitor()
monitor.run()