-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysinfo_windows.py
More file actions
192 lines (149 loc) · 6.52 KB
/
sysinfo_windows.py
File metadata and controls
192 lines (149 loc) · 6.52 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
#!/usr/bin/env python3
"""
sysinfo_windows.py — Windows system information collector.
Produces the same output structure as task4_1.sh.
Requires: psutil (auto-installed if missing)
Output: sysinfo_windows.out (same directory as this script)
"""
import os
import sys
import socket
import platform
import ipaddress
import subprocess
import time
from datetime import datetime, timezone, timedelta
# ── Auto-install psutil ───────────────────────────────────────────────────────
try:
import psutil
except ImportError:
print("psutil not found — installing...", flush=True)
subprocess.check_call([sys.executable, "-m", "pip", "install", "psutil", "-q"])
import psutil
# ── Helpers ───────────────────────────────────────────────────────────────────
_NO_DATA = {"", "not available", "not specified", "not present",
"unknown", "to be filled by o.e.m.", "default string"}
def _clean(val: str) -> str:
"""Return val stripped, or empty string if it is a DMI non-value."""
v = (val or "").strip()
return "" if v.lower() in _NO_DATA else v
def _ps(command: str) -> str:
"""Run a PowerShell command and return stripped stdout, or '' on failure."""
try:
result = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command", command],
capture_output=True, text=True, timeout=15,
)
return result.stdout.strip()
except Exception:
return ""
def _netmask_to_prefix(netmask: str) -> int:
try:
return ipaddress.IPv4Network(f"0.0.0.0/{netmask}").prefixlen
except ValueError:
return 0
# ── Hardware ──────────────────────────────────────────────────────────────────
def get_cpu() -> str:
val = _ps("(Get-CimInstance Win32_Processor | Select-Object -First 1).Name")
return _clean(val) or platform.processor() or "Unknown"
def get_ram() -> str:
mem = psutil.virtual_memory()
return f"{mem.total // (1024 ** 2)} MB"
def get_motherboard() -> str:
mfr = _clean(_ps("(Get-CimInstance Win32_BaseBoard | Select-Object -First 1).Manufacturer"))
prod = _clean(_ps("(Get-CimInstance Win32_BaseBoard | Select-Object -First 1).Product"))
if not prod:
prod = "Unknown"
return f"{mfr} {prod}".strip() if mfr else prod
def get_serial() -> str:
val = _clean(_ps("(Get-CimInstance Win32_BIOS | Select-Object -First 1).SerialNumber"))
return val or "Unknown"
# ── System ────────────────────────────────────────────────────────────────────
def get_os_distro() -> str:
val = _clean(_ps("(Get-CimInstance Win32_OperatingSystem | Select-Object -First 1).Caption"))
return val or f"{platform.system()} {platform.release()}"
def get_kernel_version() -> str:
return platform.version() or "Unknown"
def get_install_date() -> str:
# Get ISO-8601 string from PowerShell to avoid quote-escaping issues
iso = _ps(
"(Get-CimInstance Win32_OperatingSystem).InstallDate"
".ToUniversalTime().ToString('s')"
)
if iso:
try:
dt = datetime.strptime(iso, "%Y-%m-%dT%H:%M:%S")
return dt.strftime("%a %b %d %H:%M:%S UTC %Y")
except ValueError:
pass
return "Unknown"
def get_hostname() -> str:
return socket.gethostname()
def get_uptime() -> str:
elapsed_secs = int(time.time() - psutil.boot_time())
total_mins = elapsed_secs // 60
weeks = total_mins // 10080
days = (total_mins % 10080) // 1440
hours = (total_mins % 1440) // 60
mins = total_mins % 60
parts = []
if weeks: parts.append(f"{weeks} weeks")
if days: parts.append(f"{days} days")
if hours: parts.append(f"{hours} hours")
if mins: parts.append(f"{mins} minutes")
return ", ".join(parts) if parts else "0 minutes"
def get_processes() -> int:
return len(psutil.pids())
def get_users() -> int:
return len(psutil.users())
# ── Network ───────────────────────────────────────────────────────────────────
def get_network() -> list[str]:
addrs = psutil.net_if_addrs()
# Preserve interface order from net_if_stats (which reflects system order)
stats = psutil.net_if_stats()
ifaces = list(stats.keys())
# Add any interface present in addrs but not in stats
for name in addrs:
if name not in ifaces:
ifaces.append(name)
lines = []
for iface in ifaces:
ipv4_addrs = [
a for a in addrs.get(iface, [])
if a.family == socket.AF_INET
]
if ipv4_addrs:
entries = []
for a in ipv4_addrs:
prefix = _netmask_to_prefix(a.netmask) if a.netmask else 0
entries.append(f"{a.address}/{prefix}")
lines.append(f"{iface}: {', '.join(entries)}")
else:
lines.append(f"{iface}: -")
return lines
# ── Main ──────────────────────────────────────────────────────────────────────
def main():
output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"sysinfo_windows.out")
sections = [
"--- Hardware ---",
f"CPU: {get_cpu()}",
f"RAM: {get_ram()}",
f"Motherboard: {get_motherboard()}",
f"System Serial Number: {get_serial()}",
"--- System ---",
f"OS Distribution: {get_os_distro()}",
f"Kernel version: {get_kernel_version()}",
f"Installation date: {get_install_date()}",
f"Hostname: {get_hostname()}",
f"Uptime: {get_uptime()}",
f"Processes running: {get_processes()}",
f"Users logged in: {get_users()}",
"--- Network ---",
*get_network(),
]
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(sections) + "\n")
print(f"Written: {output_path}")
if __name__ == "__main__":
main()