-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpc_diagnostics.py
More file actions
316 lines (278 loc) · 10.9 KB
/
pc_diagnostics.py
File metadata and controls
316 lines (278 loc) · 10.9 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
"""
PC Hardware Diagnostics Script - System Readiness Report
Author: Callum Cummins
Requirements: psutil (pip install psutil)
Usage:
python pc_diagnostics.py # prints a Markdown report
python pc_diagnostics.py --json # prints JSON
python pc_diagnostics.py --out report.md # writes Markdown to a file
"""
from datetime import datetime, timezone
import json
import os
import platform
import shutil
import socket
import subprocess
import sys
try:
import psutil
except Exception:
print("This tool needs 'psutil'. Install with: pip install psutil", file=sys.stderr)
sys.exit(1)
def gather_gpu_info():
gpus = []
# Try NVIDIA (nvidia-smi)
try:
out = subprocess.check_output(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader"],
stderr=subprocess.STDOUT, text=True, timeout=5)
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 2:
gpus.append({"vendor": "NVIDIA", "name": parts[0], "memory": parts[1]})
except Exception:
pass
# macOS
if not gpus and platform.system() == "Darwin":
try:
out = subprocess.check_output(["system_profiler", "SPDisplaysDataType", "-json"], text=True, timeout=10)
data = json.loads(out)
displays = data.get("SPDisplaysDataType", [])
for d in displays:
gpus.append({
"vendor": d.get("sppci_vendor", "Apple/Unknown"),
"name": d.get("sppci_model", d.get("_name", "GPU")),
"memory": d.get("spdisplays_vram", "Unknown")
})
except Exception:
pass
# Linux
if not gpus and platform.system() == "Linux":
try:
out = subprocess.check_output(["bash", "-lc", "lspci | grep -i 'vga\\|3d\\|display'"],
text=True, timeout=5)
for line in out.strip().splitlines():
gpus.append({"vendor": "Unknown", "name": line.strip(), "memory": "Unknown"})
except Exception:
pass
return gpus
def get_cpu_model():
cpu = platform.processor() or ""
if not cpu and platform.system() == "Linux":
try:
with open("/proc/cpuinfo", "r") as f:
for ln in f:
if "model name" in ln:
return ln.split(":", 1)[1].strip()
except Exception:
pass
return cpu or "Unknown CPU"
def gather_temperatures():
temps = {}
try:
t = psutil.sensors_temperatures(fahrenheit=False)
for key, entries in t.items():
temps[key] = []
for e in entries:
temps[key].append({
"label": e.label or key,
"current": e.current,
"high": e.high,
"critical": e.critical
})
except Exception:
temps = {}
return temps
def seconds_to_hms(sec):
sec = int(sec)
h = sec // 3600
m = (sec % 3600) // 60
s = sec % 60
return f"{h}h {m}m {s}s"
def readiness_checks(summary):
checks = []
# Disk: at least 20% free on root
root = None
for d in summary["disks"]:
if d.get("mountpoint") in ("/", "C:\\"):
root = d
break
if root:
if root["percent_free"] >= 20:
checks.append({"name": "Disk space (root)", "status": "OK", "detail": f"{root['percent_free']:.1f}% free"})
else:
checks.append({"name": "Disk space (root)", "status": "ATTENTION", "detail": f"Low free space: {root['percent_free']:.1f}%"})
else:
checks.append({"name": "Disk space (root)", "status": "UNKNOWN", "detail": "Root partition not found"})
# RAM: at least 15% available
if summary["memory"]["percent_available"] >= 15:
checks.append({"name": "Memory availability", "status": "OK", "detail": f"{summary['memory']['percent_available']:.1f}% available"})
else:
checks.append({"name": "Memory availability", "status": "ATTENTION", "detail": f"Low available memory: {summary['memory']['percent_available']:.1f}%"})
# Uptime: less than 7 days
if summary["uptime_seconds"] <= 7*24*3600:
checks.append({"name": "System uptime", "status": "OK", "detail": seconds_to_hms(summary['uptime_seconds'])})
else:
checks.append({"name": "System uptime", "status": "INFO", "detail": f"High uptime: {seconds_to_hms(summary['uptime_seconds'])} (consider reboot if issues arise)"})
# Temperatures
overheat = False
for _, entries in summary.get("temperatures", {}).items():
for e in entries:
if e["current"] and e["current"] >= 85:
overheat = True
break
if summary.get("temperatures"):
if overheat:
checks.append({"name": "CPU/GPU temperatures", "status": "ATTENTION", "detail": "One or more sensors ≥ 85°C"})
else:
checks.append({"name": "CPU/GPU temperatures", "status": "OK", "detail": "All reported sensors < 85°C"})
else:
checks.append({"name": "CPU/GPU temperatures", "status": "UNKNOWN", "detail": "No temperature sensors available"})
return checks
def gather_summary():
boot_time = datetime.fromtimestamp(psutil.boot_time(), tz=timezone.utc)
now = datetime.now(timezone.utc)
uptime = (now - boot_time).total_seconds()
cpu_freq = psutil.cpu_freq()
cpu = {
"model": get_cpu_model(),
"cores_physical": psutil.cpu_count(logical=False) or 0,
"cores_logical": psutil.cpu_count(logical=True) or 0,
"current_freq_mhz": cpu_freq.current if cpu_freq else None,
"max_freq_mhz": cpu_freq.max if cpu_freq else None,
"load_percent_per_core": psutil.cpu_percent(percpu=True, interval=0.5),
"overall_load_percent": psutil.cpu_percent(interval=0.5),
}
vm = psutil.virtual_memory()
mem = {
"total_gb": vm.total / (1024**3),
"available_gb": vm.available / (1024**3),
"percent_used": vm.percent,
"percent_available": 100 - vm.percent
}
disks = []
for p in psutil.disk_partitions(all=False):
try:
usage = psutil.disk_usage(p.mountpoint)
disks.append({
"device": p.device,
"mountpoint": p.mountpoint,
"fstype": p.fstype,
"total_gb": usage.total / (1024**3),
"used_gb": usage.used / (1024**3),
"free_gb": usage.free / (1024**3),
"percent_used": usage.percent,
"percent_free": 100 - usage.percent
})
except Exception:
continue
net_stats = psutil.net_if_stats()
net_addrs = psutil.net_if_addrs()
net = []
for name, stats in net_stats.items():
addrs = [a.address for a in net_addrs.get(name, []) if a.family in (socket.AF_INET, socket.AF_INET6)]
net.append({
"interface": name,
"isup": stats.isup,
"speed_mbps": stats.speed,
"mtu": stats.mtu,
"addresses": addrs
})
gpu = gather_gpu_info()
temps = gather_temperatures()
summary = {
"generated_at": now.isoformat(),
"hostname": socket.gethostname(),
"os": {
"system": platform.system(),
"release": platform.release(),
"version": platform.version(),
"platform": platform.platform(),
},
"boot_time_utc": boot_time.isoformat(),
"uptime_seconds": uptime,
"cpu": cpu,
"memory": mem,
"disks": disks,
"network": net,
"gpus": gpu,
"temperatures": temps,
}
return summary
def format_markdown(summary):
checks = readiness_checks(summary)
lines = []
lines.append(f"# System Readiness Report")
lines.append(f"*Generated:* {summary['generated_at']} ")
lines.append(f"*Host:* `{summary['hostname']}` ")
lines.append(f"*OS:* {summary['os']['platform']}")
lines.append("")
lines.append("## Readiness Checks")
for c in checks:
emoji = {"OK": "✔️", "ATTENTION": "⚠️", "INFO": "ℹ️", "UNKNOWN": "❓"}.get(c["status"], "•")
lines.append(f"- {emoji} **{c['name']}** — {c['status']}: {c['detail']}")
lines.append("")
lines.append("## CPU")
cpu = summary["cpu"]
lines.append(f"- **Model:** {cpu['model']}")
lines.append(f"- **Cores:** {cpu['cores_physical']} physical / {cpu['cores_logical']} logical")
if cpu["current_freq_mhz"]:
lines.append(f"- **Frequency:** {cpu['current_freq_mhz']:.0f} MHz (max {cpu['max_freq_mhz']:.0f} MHz)")
lines.append(f"- **Overall Load:** {cpu['overall_load_percent']:.1f}%")
lines.append("")
lines.append("## Memory")
mem = summary["memory"]
lines.append(f"- **Total:** {mem['total_gb']:.2f} GB")
lines.append(f"- **Available:** {mem['available_gb']:.2f} GB ({mem['percent_available']:.1f}% available)")
lines.append("")
lines.append("## Disks")
for d in summary["disks"]:
lines.append(f"- **{d['mountpoint']}** — {d['total_gb']:.1f} GB total, {d['free_gb']:.1f} GB free ({d['percent_free']:.1f}% free)")
lines.append("")
lines.append("## Network Interfaces")
for n in summary["network"]:
addrs = ", ".join(n["addresses"]) if n["addresses"] else "No IP"
lines.append(f"- **{n['interface']}** — {'up' if n['isup'] else 'down'}, {n['speed_mbps']} Mbps, MTU {n['mtu']}, {addrs}")
lines.append("")
lines.append("## GPUs")
if summary["gpus"]:
for g in summary["gpus"]:
lines.append(f"- **{g['vendor']}** {g['name']} — {g['memory']}")
else:
lines.append("- No GPU information available")
lines.append("")
lines.append("## Temperatures")
if summary["temperatures"]:
for key, entries in summary["temperatures"].items():
lines.append(f"- **{key}**")
for e in entries:
hi = f", high {e['high']}°C" if e.get("high") else ""
cr = f", crit {e['critical']}°C" if e.get("critical") else ""
lines.append(f" - {e['label']}: {e['current']}°C{hi}{cr}")
else:
lines.append("- No temperature sensors reported")
return "\n".join(lines)
def main(argv):
out_path = None
as_json = False
if "--json" in argv:
as_json = True
if "--out" in argv:
try:
out_path = argv[argv.index("--out") + 1]
except Exception:
print("Usage: --out <file>", file=sys.stderr)
sys.exit(2)
summary = gather_summary()
if as_json:
output = json.dumps(summary, indent=2)
else:
output = format_markdown(summary)
if out_path:
with open(out_path, "w", encoding="utf-8") as f:
f.write(output)
print(f"Wrote report to: {out_path}")
else:
print(output)
if __name__ == "__main__":
main(sys.argv[1:])