-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetserial.py
More file actions
427 lines (335 loc) · 15.3 KB
/
getserial.py
File metadata and controls
427 lines (335 loc) · 15.3 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import os
import subprocess
import tempfile
from datetime import datetime
import requests
import socket
import winreg
import re
import json
# Function to get the public IP address
def get_public_ip():
try:
response = requests.get('https://api.ipify.org')
return response.text
except Exception as e:
return f"Error getting public IP address: {e}"
# Function to get the router's MAC address
def get_router_mac_address():
try:
arp_output = subprocess.getoutput('arp -a')
for line in arp_output.split('\n'):
# Continue past headers or empty lines
if 'Interface' in line or line.strip() == '':
continue
parts = line.split()
# Ensure there are at least 3 parts to unpack (IP, MAC, and Type)
if len(parts) < 3:
continue # Skip lines that don't have enough data
ip_address, mac_address, type = parts[0], parts[1], parts[2]
# Look for a dynamic entry typically associated with a router in a home network
if ip_address.startswith('192.168.') and type.lower() == 'dynamic' or type.lower() == 'dinamico' :
return ip_address, mac_address
except Exception as e:
return f"Error in getting router MAC address: {e}"
return None, None # Return None if no suitable entry was found
# Function to get the local IP address
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
finally:
s.close()
return local_ip
# Function to get Microsoft accounts
def get_microsoft_accounts():
try:
with tempfile.NamedTemporaryFile(delete=False, mode='w+', suffix='.txt') as temp_file:
temp_file_path = temp_file.name
batch_script = f"""
@echo off
net user > "{temp_file_path}"
"""
batch_file_path = os.path.join(tempfile.gettempdir(), 'get_users.bat')
with open(batch_file_path, 'w') as batch_file:
batch_file.write(batch_script)
subprocess.run(['powershell', '-Command', 'Start-Process', 'cmd.exe', '-ArgumentList', f"/c {batch_file_path}", '-Verb', 'RunAs'])
with open(temp_file_path, 'r') as temp_file:
users_output = temp_file.read()
users_lines = users_output.splitlines()
start_listing = False
accounts = []
for line in users_lines:
if '----------------' in line:
start_listing = not start_listing
continue
if start_listing and line.strip():
accounts.append(line.strip())
microsoft_accounts = [acc for acc in accounts if '@' in acc]
if microsoft_accounts:
result = "Microsoft accounts on the system:\n" + "\n".join(microsoft_accounts) + "\n"
else:
result = "No Microsoft accounts on the system.\n"
os.remove(temp_file_path)
os.remove(batch_file_path)
return result
except Exception as e:
return f"An error occurred: {e}"
# Function to get registry value
def get_registry_value(key, subkey, value_name):
try:
registry_key = winreg.OpenKey(key, subkey, 0, winreg.KEY_READ)
value, regtype = winreg.QueryValueEx(registry_key, value_name)
winreg.CloseKey(registry_key)
return value
except WindowsError:
return None
import winreg
def get_registry_value(key, subkey, value_name):
try:
with winreg.OpenKey(key, subkey) as registry_key:
value, regtype = winreg.QueryValueEx(registry_key, value_name)
return value
except FileNotFoundError:
return "Not found"
except Exception as e:
return f"Error: {e}"
def get_registry_data():
key = winreg.HKEY_LOCAL_MACHINE
registry_data = {
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion": ["InstallationID", "ProductID", "BuildGUID", "RegisteredOrganization", "RegisteredOwner"],
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform": ["BackupProductKeyDefault"],
r"SOFTWARE\Microsoft\SQMClient": ["MachineId"],
r"SYSTEM\CurrentControlSet\Control\IDConfigDB\Hardware Profiles\0001": ["HwProfileGuid", "BIOSReleaseDate", "BIOSVersion", "ComputerHardwareId"],
r"SOFTWARE\Microsoft\Cryptography": ["MachineGuid"],
r"SYSTEM\CurrentControlSet\Control\Nsi\{eb004a03-9b1a-11d4-9123-0050047759bc}\26": ["VariableId"],
r"HARDWARE\DESCRIPTION\System\BIOS": ["SystemFamily", "SystemManufacturer", "SystemProductName", "SystemSKU", "SystemVersion", "BaseBoardManufacturer", "BaseBoardProduct", "BaseBoardVersion", "BIOSReleaseDate", "BIOSVendor"],
r"SOFTWARE\NVIDIA Corporation\Global": ["ClientUUID"],
r"SOFTWARE\NVIDIA Corporation\Global\CoProcManager": ["ChipsetMatchID"],
}
registry_output = ""
for subkey, values in registry_data.items():
for value_name in values:
value = get_registry_value(key, subkey, value_name)
registry_output += f"{value_name}: {value}\n"
return registry_output
def get_usb_devices():
cmd = [
"powershell",
"Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like '*USB*' } | "
"Select-Object InstanceId, FriendlyName | Format-Table -HideTableHeaders"
]
result = subprocess.run(cmd, capture_output=True, text=True).stdout
output = ""
for line in result.splitlines():
line = line.strip()
if not line:
continue
# separa InstanceId e FriendlyName
try:
instance_id = line[:line.index(" ")].strip()
friendly_name = line[line.index(" "):].strip()
except:
continue
# Estrazione VID e PID da InstanceId
match = re.search(r"VID_([0-9A-Fa-f]+).*PID_([0-9A-Fa-f]+)", instance_id)
if match:
vid = match.group(1)
pid = match.group(2)
else:
vid = "N/A"
pid = "N/A"
# UNA sola riga:
output += f"{friendly_name} | VID: {vid} | PID: {pid}\n"
return output
def get_network_mac_address():
try:
output = subprocess.getoutput("getmac /fo csv /v")
lines = output.splitlines()
mac_addresses = []
# Salta la prima riga (intestazione)
for line in lines[1:]:
parts = line.replace('"', '').split(',')
if len(parts) > 2:
mac_address = parts[1].strip()
name = parts[2].strip()
if mac_address and mac_address != 'N/A':
# Prima MAC, poi nome
mac_addresses.append(f"MAC {name} {mac_address}")
if mac_addresses:
mac_output = "\n".join(mac_addresses) + "\n"
else:
mac_output = "No MAC addresses found.\n"
return mac_output
except Exception as e:
return f"Error getting network MAC addresses: {e}"
def get_disks_and_volumes_info(run_powershell_command):
"""
Restituisce informazioni dischi e volumi in formato leggibile:
Name: <volume_name> | SerialNumber: <disk_serial> | VolumeSerialNumber: <volume_serial_formattato>
"""
# Funzione interna per formattare il seriale del volume
def format_volume_serial(serial):
s = serial.strip()
if len(s) == 8:
return s[:4] + "-" + s[4:]
return s
# 1. Seriali dei dischi fisici
disk_info = run_powershell_command(
"Get-WmiObject Win32_DiskDrive | Select-Object SerialNumber | ConvertTo-Json"
)
disks = json.loads(disk_info)
if isinstance(disks, dict):
disks = [disks]
# 2. Informazioni volumi logici
volume_info = run_powershell_command(
"Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID, VolumeName, VolumeSerialNumber | ConvertTo-Json"
)
volumes = json.loads(volume_info)
if isinstance(volumes, dict):
volumes = [volumes]
# 3. Associa dischi e volumi
output_lines = []
for i, disk in enumerate(disks):
disk_serial = disk.get("SerialNumber", "").strip()
if i < len(volumes):
vol = volumes[i]
volume_name = vol.get("VolumeName", "").strip()
volume_serial = format_volume_serial(vol.get("VolumeSerialNumber", "").strip())
line = f"Name: {volume_name} | SerialNumber: {disk_serial} | VolumeSerialNumber: {volume_serial}"
else:
line = f"Name: None | SerialNumber: {disk_serial} | VolumeSerialNumber: None"
output_lines.append(line)
return "\n".join(output_lines)
def get_tpm_info():
try:
out = subprocess.getoutput('PowerShell -Command "Get-TpmEndorsementKeyInfo -Hash Sha256"')
except Exception:
out = ""
ek_m = re.search(r'PublicKeyHash\s*:\s*(\S+)', out)
ek = ek_m.group(1) if ek_m else "Not found"
serials = re.findall(r'\[Serial Number\]\s*\n\s*([A-F0-9]+)', out, re.IGNORECASE)
serials_text = ", ".join(serials) if serials else "None"
try:
pcr_out = subprocess.getoutput("tpmtool printpcr sha256")
except Exception:
pcr_out = ""
pcrs = {}
for i in range(8):
m = re.search(rf"PCR\[{i:02d}\]:\s*([0-9a-fA-F]+)", pcr_out)
pcrs[i] = m.group(1).lower() if m else "Not found"
lines = []
lines.append(f"EK Public SHA256: {ek}")
lines.append(f"Serial Number: {serials_text}")
for i in range(8):
lines.append(f"PCR{i}: {pcrs[i]}")
return "\n".join(lines)
def get_monitor_info(run_powershell_command):
ps = r'''
function Decode-Ascii($bytes) {
$chars = @()
foreach ($b in $bytes) {
if ($b -eq 0x00 -or $b -eq 0x0A) { continue }
$chars += [char]$b
}
return ($chars -join '')
}
# --- PRIMO TENTATIVO: WmiMonitorID ---
$mon = Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorID | Select-Object -First 1
$serial_text = ""
if ($mon) {
$serial_text = ($mon.SerialNumber -ne 0 | ForEach-Object {[char]$_}) -join ''
}
$serial_raw = "N/A"
# --- SE NON TROVATO, LEGGI REGISTRO (CRU) ---
if ($serial_text -eq "") {
$items = Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Enum\DISPLAY" -Recurse |
Where-Object { $_.PSChildName -eq "Device Parameters" }
foreach ($item in $items) {
try {
$edid = (Get-ItemProperty -Path $item.PSPath -Name EDID).EDID
} catch { continue }
for ($i=54; $i -lt 126; $i+=18) {
if ($edid[$i+3] -eq 0xFF) {
# RAW HEX (ID SERIAL)
$raw_bytes = $edid[($i+5)..($i+17)]
$serial_raw = ($raw_bytes | ForEach-Object { $_.ToString("X2") }) -join "-"
# TESTO DECODIFICATO
$decoded = Decode-Ascii $raw_bytes
if ($decoded.Length -gt 0) {
$serial_text = $decoded
}
}
}
}
}
"Serial Number: $serial_text`nIDSerial: $serial_raw"
'''
result = run_powershell_command(ps)
print(result)
return result
OUTPUT_FILE = "getSerial_py.txt"
current_username = os.getlogin()
current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Funzione per eseguire i comandi PowerShell e ottenere l'output
def run_powershell_command(command):
return subprocess.getoutput(f"powershell -Command \"{command}\"")
with open(OUTPUT_FILE, "w") as output_file:
output_file.write(f"Data e ora di creazione: {current_datetime}\n\n")
# Ottiene il nome del sistema
cs_name = run_powershell_command("(Get-ComputerInfo -Property CsName).CsName").strip()
output_file.write(f"ComputerSystem Name: {cs_name}\n\n")
# Ottiene gli account utente
#output_file.write("User Accounts (filtered):\n")
#user_accounts = run_powershell_command("Get-LocalUser | Select-Object Name, SID | Format-Table -HideTableHeaders")
#output_file.write(user_accounts + "\n\n")
# BIOS Serial Number
bios_serial = run_powershell_command("(Get-WmiObject Win32_BIOS).SerialNumber").strip()
output_file.write(f"BIOS Serial Number: {bios_serial}\n\n")
# CPU Serial Number
cpu_serial = run_powershell_command("(Get-WmiObject Win32_Processor).ProcessorId").strip()
output_file.write(f"CPU Serial Number: {cpu_serial}\n\n")
# System Enclosure Serial Number
system_enclosure_serial = run_powershell_command("(Get-WmiObject Win32_SystemEnclosure).SerialNumber").strip()
output_file.write(f"System Enclosure Serial Number: {system_enclosure_serial}\n\n")
# BaseBoard Serial Number
baseboard_serial = run_powershell_command("(Get-WmiObject Win32_BaseBoard).SerialNumber").strip()
output_file.write(f"BaseBoard Serial Number: {baseboard_serial}\n\n")
# Memory Chip Serial Numbers (più valori → uniti in una sola linea)
memory_chip_serial = run_powershell_command("(Get-WmiObject Win32_PhysicalMemory).SerialNumber")
memory_chip_serial = " ".join(memory_chip_serial.split()) # pulisce le newline
output_file.write(f"Memory Chip Serial Numbers: {memory_chip_serial}\n\n")
# Ottiene i numeri di serie dei dischi rigidi
disks_and_volumes = get_disks_and_volumes_info(run_powershell_command)
output_file.write("HDD " + disks_and_volumes + "\n\n")
public_ip = get_public_ip()
output_file.write(f"Indirizzo IP pubblico: {public_ip}\n\n")
local_ip = get_local_ip()
output_file.write(f"Indirizzo IP locale: {local_ip}\n\n")
router_ip, router_mac = get_router_mac_address()
if router_mac:
output_file.write(f"Indirizzo IP del router: {router_ip}\n")
output_file.write(f"Indirizzo MAC del router: {router_mac}\n\n")
else:
output_file.write("Indirizzo MAC del router non trovato.\n\n")
#output_file.write("\n\nMAC Addresses:\n")
output_file.write(get_network_mac_address())
#output_file.write("\n\nNVIDIA GPU UUID Information:\n")
#output_file.write(subprocess.getoutput('nvidia-smi --query-gpu=gpu_name,uuid --format=csv'))
gpu_info = subprocess.getoutput('nvidia-smi --query-gpu=gpu_name,uuid --format=csv,noheader')
output_file.write("GPU UUID: "+ gpu_info + "\n")
powershell_command = 'PowerShell -Command "Get-WmiObject -Namespace root\wmi -Class WmiMonitorID | ForEach-Object { [System.Text.Encoding]::ASCII.GetString($_.SerialNumberID) }"'
output_file.write("Monitor ID Serial Numbers:" + subprocess.getoutput(powershell_command))
output_file.write("\nTpmEndorsementKeyInfo:\n")
output_file.write(get_tpm_info())
output_file.write("\n\nMicrosoft Accounts:\n")
output_file.write(get_microsoft_accounts())
output_file.write("\n\nRegistry Data:\n")
output_file.write(get_registry_data())
# Ottiene UUID UEFI
uefi_uuid = run_powershell_command("(Get-CimInstance -Class Win32_ComputerSystemProduct).UUID")
output_file.write("UUID UEFI: " + uefi_uuid + "\n\n")
output_file.write("\n\nUSB Devices:\n")
output_file.write(get_usb_devices())
print(f"Results have been saved to {OUTPUT_FILE}")