Repository navigation
Expand file tree
/
Copy pathhost_diagnostics.py
More file actions
91 lines (79 loc) · 3.08 KB
/
Copy pathhost_diagnostics.py
File metadata and controls
91 lines (79 loc) · 3.08 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
"""Read-only Windows host snapshot for the desktop, HTTP API and MCP."""
from datetime import datetime, timezone
import socket
try:
import psutil
except ImportError:
psutil = None
def collect(tasks, *, ports=()):
report = {
"host": socket.gethostname(),
"sampled_at": datetime.now(timezone.utc).isoformat(),
"perspective": "target_host",
"client_reachability": "not_verified",
"errors": {},
}
def sample(name, reader):
try:
report[name] = reader()
except (OSError, RuntimeError, ValueError, AttributeError) as exc:
report[name] = None
report["errors"][name] = str(exc)
except Exception as exc:
if psutil is None or not isinstance(exc, psutil.Error):
raise
report[name] = None
report["errors"][name] = str(exc)
sample("tasks", tasks)
if psutil is None:
report["errors"]["system"] = "psutil is unavailable"
return report
sample("cpu_percent", lambda: psutil.cpu_percent(interval=0.15))
sample("memory", lambda: {
"total_bytes": (memory := psutil.virtual_memory()).total,
"available_bytes": memory.available,
})
sample("boot_time", lambda: datetime.fromtimestamp(psutil.boot_time(), timezone.utc).isoformat())
def disks():
rows = []
for partition in psutil.disk_partitions(all=False):
row = {"mount": partition.mountpoint}
try:
usage = psutil.disk_usage(partition.mountpoint)
row.update(total_bytes=usage.total, free_bytes=usage.free)
except OSError as exc:
row["error"] = str(exc)
rows.append(row)
return rows
sample("disks", disks)
for service in ("TermService", "sshd"):
def service_status(name=service):
try:
return psutil.win_service_get(name).status()
except psutil.NoSuchProcess:
return "not_installed"
sample(service, service_status)
watched = sorted({22, 3389, *ports})
def listeners():
rows = []
names = {}
sockets = sorted({
(entry.laddr.port, entry.laddr.ip, entry.pid)
for entry in psutil.net_connections(kind="tcp")
if entry.status == psutil.CONN_LISTEN and entry.laddr
}, key=lambda entry: (entry[0] not in watched, entry[0], entry[1], entry[2] or 0))
for port, address, pid in sockets[:256]:
if pid not in names:
try:
names[pid] = psutil.Process(pid).name() if pid is not None else None
except psutil.Error:
names[pid] = None
rows.append({"port": port, "address": address, "pid": pid, "process": names[pid]})
report["listener_list_truncated"] = len(sockets) > len(rows)
report["watched_ports"] = [
{"port": port, "listening": any(entry[0] == port for entry in sockets)}
for port in watched
]
return rows
sample("listeners", listeners)
return report