-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex2sid.py
More file actions
676 lines (582 loc) · 28.8 KB
/
Copy pathhex2sid.py
File metadata and controls
676 lines (582 loc) · 28.8 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#!/usr/bin/env python3
import struct
import argparse
import sys
import os
try:
from termcolor import colored
COLOR_AVAILABLE = True
except ImportError:
COLOR_AVAILABLE = False
# Fallback function if termcolor is not available
def colored(text, color=None, attrs=None):
return text
# Helper functions for colored output
def print_success(msg):
"""Print success message in green"""
print(colored(f"[+] {msg}", "green", attrs=["bold"]))
def print_error(msg):
"""Print error message in red"""
print(colored(f"[-] {msg}", "red", attrs=["bold"]))
def print_info(msg):
"""Print info message in blue"""
print(colored(f"[*] {msg}", "blue", attrs=["bold"]))
def print_warning(msg):
"""Print warning message in yellow"""
print(colored(f"[!] {msg}", "yellow", attrs=["bold"]))
try:
# Try different import methods depending on impacket version
MSSQL = None
MSSQLConnection = None
# Method 1: impacket.mssql
try:
from impacket.mssql import MSSQL
except (ImportError, AttributeError):
pass
# Method 2: impacket.tds (Tabular Data Stream - used by impacket for MSSQL)
if MSSQL is None:
try:
from impacket import tds
if hasattr(tds, 'MSSQL'):
MSSQL = tds.MSSQL
elif hasattr(tds, 'MSSQLConnection'):
MSSQLConnection = tds.MSSQLConnection
except (ImportError, AttributeError):
pass
# Method 3: impacket.tdsbase
if MSSQL is None and MSSQLConnection is None:
try:
from impacket import tdsbase
if hasattr(tdsbase, 'MSSQL'):
MSSQL = tdsbase.MSSQL
elif hasattr(tdsbase, 'MSSQLConnection'):
MSSQLConnection = tdsbase.MSSQLConnection
except (ImportError, AttributeError):
pass
# Import SID class for RID brute force
try:
from impacket.dcerpc.v5.dtypes import SID
SID_AVAILABLE = True
except ImportError:
SID_AVAILABLE = False
# Method 4: Search all sub-modules
if MSSQL is None and MSSQLConnection is None:
try:
import impacket
import pkgutil
import os
impacket_dir = os.path.dirname(impacket.__file__)
for importer, modname, ispkg in pkgutil.iter_modules([impacket_dir]):
if 'mssql' in modname.lower() or 'tds' in modname.lower():
try:
mod = __import__(f'impacket.{modname}', fromlist=[modname])
if hasattr(mod, 'MSSQL'):
MSSQL = mod.MSSQL
break
elif hasattr(mod, 'MSSQLConnection'):
MSSQLConnection = mod.MSSQLConnection
break
except:
continue
except:
pass
if MSSQL is None and MSSQLConnection is None:
raise ImportError("Unable to find MSSQL or MSSQLConnection class in impacket")
# If MSSQLConnection was found but not MSSQL, use MSSQLConnection
if MSSQL is None and MSSQLConnection is not None:
MSSQL = MSSQLConnection
if MSSQL is None:
raise ImportError("MSSQL class could not be loaded")
IMPACKET_AVAILABLE = True
except ImportError as e:
IMPACKET_AVAILABLE = False
IMPACKET_ERROR = str(e)
# Import SID class for RID brute force (separate try/except)
try:
from impacket.dcerpc.v5.dtypes import SID
SID_AVAILABLE = True
except ImportError:
SID_AVAILABLE = False
def hex_to_sid(hex_str):
"""Convert a hexadecimal string to a formatted Windows SID."""
try:
# Nettoyage de la chaîne
hex_str = hex_str.strip().lower()
if hex_str.startswith('0x'):
hex_str = hex_str[2:]
data = bytes.fromhex(hex_str)
if len(data) < 8:
return "Error: Data too short"
revision = data[0]
sub_authority_count = data[1]
# L'autorité est sur 6 octets (big-endian)
identifier_authority = struct.unpack('>Q', b'\x00\x00' + data[2:8])[0]
sub_authorities = []
for i in range(sub_authority_count):
start = 8 + (i * 4)
end = start + 4
# Les sous-autorités sont sur 4 octets (little-endian)
sub_authorities.append(struct.unpack('<I', data[start:end])[0])
return f"S-{revision}-{identifier_authority}-" + "-".join(map(str, sub_authorities))
except Exception as e:
return f"Conversion error: {str(e)}"
def rid_brute_force(mssql, domain_sid, max_rid=5000, verbose=False):
"""Perform RID brute force to find users/groups by combining domain SID with RIDs."""
if not SID_AVAILABLE:
print_error("SID class from impacket.dcerpc.v5.dtypes not available")
return []
entries = []
try:
# Query domain name
domain_result = mssql.sql_query("SELECT DEFAULT_DOMAIN()")
if not domain_result or len(domain_result) == 0:
print_error("Could not retrieve domain name")
return []
domain = domain_result[0].get("") or domain_result[0].get("DEFAULT_DOMAIN()", "")
if not domain or domain == "NULL":
print_error("Domain not found or server not domain joined")
return []
if verbose:
print_info(f"Domain found: {domain}")
print_info(f"Domain SID: {domain_sid}")
print_info(f"Starting RID brute force (0-{max_rid})...")
so_far = 0
simultaneous = 1000 # Query 1000 RIDs at a time
for _j in range(max_rid // simultaneous + 1):
sids_to_check = (max_rid - so_far) % simultaneous if (max_rid - so_far) // simultaneous == 0 else simultaneous
if sids_to_check == 0:
break
# Batch query multiple SIDs at a time
sid_queries = [f"SELECT SUSER_SNAME(SID_BINARY(N'{domain_sid}-{i:d}'))" for i in range(so_far, so_far + sids_to_check)]
query_string = ";".join(sid_queries)
try:
raw_output = mssql.sql_query(query_string)
for n, item in enumerate(raw_output):
username = item.get("") or item.get("SUSER_SNAME", "")
if not username or username == "NULL":
continue
rid = so_far + n
full_sid = f"{domain_sid}-{rid}"
# Extract username (remove domain prefix if present)
if "\\" in username:
username_only = username.split("\\")[1]
else:
username_only = username
entries.append({
"rid": rid,
"domain": domain,
"username": username,
"username_only": username_only,
"full_sid": full_sid
})
if verbose:
print_success(f"{rid}: {username}")
except Exception as e:
if verbose:
print_warning(f"Error querying RIDs {so_far}-{so_far + sids_to_check}: {e}")
continue
so_far += simultaneous
# Progress indicator
if verbose and so_far % 5000 == 0:
print_info(f"Progress: {so_far}/{max_rid} RIDs checked, {len(entries)} found")
return entries
except Exception as e:
print_error(f"Error during RID brute force: {e}")
if verbose:
import traceback
traceback.print_exc()
return []
def fetch_sids_from_mssql(host, port, username, password, domain=None, hashes=None,
windows_auth=None, query=None, verbose=False, rid_brute=False, max_rid=5000):
"""Retrieves SIDs from an MSSQL server using impacket."""
if not IMPACKET_AVAILABLE:
print_error("Error: impacket library is not installed or MSSQL class not found.")
print_error("Install it with: pip install impacket")
if 'IMPACKET_ERROR' in globals():
print_error(f"Error details: {IMPACKET_ERROR}")
# Attempt detailed diagnostics
try:
import impacket
print_info(f"impacket installed: {impacket.__file__}")
impacket_dir = os.path.dirname(impacket.__file__)
print_info(f"impacket directory: {impacket_dir}")
# List all available modules
print_info("Available modules in impacket:")
try:
import pkgutil
for importer, modname, ispkg in pkgutil.iter_modules([impacket_dir]):
print(f" - impacket.{modname} (package: {ispkg})")
if 'mssql' in modname.lower() or 'tds' in modname.lower():
try:
mod = __import__(f'impacket.{modname}', fromlist=[modname])
attrs = [x for x in dir(mod) if not x.startswith('_') and x[0].isupper()]
if attrs:
print(f" → Attributs: {attrs}")
if hasattr(mod, 'MSSQL'):
print(f" ✓ MSSQL class found!")
except Exception as e:
print(colored(f" → Error: {e}", "red"))
except Exception as e:
print_error(f"Error during exploration: {e}")
# Test known modules
modules_to_test = ['mssql', 'mssqlserver', 'tds', 'tdsbase']
for mod_name in modules_to_test:
try:
mod = __import__(f'impacket.{mod_name}', fromlist=[mod_name])
print_info(f"Module impacket.{mod_name} found")
attrs = [x for x in dir(mod) if not x.startswith('_')]
print(colored(f" → Attributes: {attrs[:20]}...", "cyan")) # Limit display
if hasattr(mod, 'MSSQL'):
print(colored(f" ✓ MSSQL class found in impacket.{mod_name}", "green"))
except ImportError as e:
pass # Module doesn't exist, that's normal
except ImportError:
print("[-] impacket module is not installed")
sys.exit(1)
try:
# Préparation des identifiants
lmhash = ""
nthash = ""
if hashes:
if ':' in hashes:
lmhash, nthash = hashes.split(':')
else:
nthash = hashes
# MSSQL Connection - Using the same method as NetExec
# impacket.tds MSSQL class expects (host, port, remoteName)
# remoteName can be the hostname or None (will be detected automatically)
# If a domain is specified, we can use the hostname, otherwise leave None
remote_name = host # Use host by default, will be used if necessary
# Create MSSQL instance
mssql = MSSQL(host, port, remote_name)
# Connect to server
# In some versions of impacket, connect() may not exist or have a different signature
# Try calling connect() without arguments, or connection will happen during login()
if hasattr(mssql, 'connect'):
try:
# Try with NetExec signature (timeout as positional argument)
sig = mssql.connect.__code__.co_argcount
if sig > 1: # If connect takes arguments (in addition to self)
mssql.connect(10) # timeout
else:
mssql.connect() # without arguments
except (TypeError, AttributeError):
# If connect() doesn't exist or has a different signature,
# connection will probably happen during login()
pass
# Prepare hashes for authentication
hash_string = None
if nthash:
if lmhash:
hash_string = f"{lmhash}:{nthash}"
else:
hash_string = f":{nthash}"
# Authentication
# login() signature: login(database, username, password, domain, hash, windows_auth)
# database can be None to use default database
# By default, use Windows authentication (like NetExec)
# windows_auth=None means "auto" (try Windows first)
# windows_auth=True means "force Windows"
# windows_auth=False means "force SQL Server"
use_windows_auth = True # By default, use Windows auth
if windows_auth is False:
use_windows_auth = False
elif windows_auth is True:
use_windows_auth = True
# If windows_auth is None, use True by default (like NetExec)
domain_for_auth = domain if domain else ""
# Try authentication
res = mssql.login(None, username, password, domain_for_auth, hash_string, use_windows_auth)
if res is not True:
error_msg = "Authentication failed"
if hasattr(mssql, 'lastError') and mssql.lastError:
error_msg += f": {mssql.lastError}"
# If we used Windows auth and it failed, suggest trying SQL auth
if use_windows_auth and not windows_auth: # If it was in auto mode
error_msg += "\n[*] Tip: If this is a local SQL Server user, try with --no-windows-auth"
raise Exception(error_msg)
# Default SQL query if none provided
if not query:
query = "SELECT name, master.dbo.fn_varbintohexstr(sid) AS sidhex FROM sys.server_principals WHERE sid IS NOT NULL;"
# Execute query
print_success(f"Connected to {host}:{port}")
print_success("Executing SQL query...")
# Execute SQL query with impacket
# sql_query() directly returns a list of dictionaries
results = mssql.sql_query(query)
# Check for errors
if hasattr(mssql, 'lastError') and mssql.lastError:
raise Exception(f"SQL error: {mssql.lastError}")
# Debug: display raw results (only if verbose or environment variable enabled)
debug_mode = verbose or os.environ.get('HEX2SID_DEBUG', '0') == '1'
if debug_mode:
if not results:
print_info("Debug: No results returned by query")
else:
print_info(f"Debug: {len(results)} row(s) returned")
if len(results) > 0:
print_info(f"Debug: First result (type: {type(results[0])}): {results[0]}")
if isinstance(results[0], dict):
print_info(f"Debug: Dictionary keys: {list(results[0].keys())}")
# Process results
# Results are dictionaries with column names as keys
sids_found = []
filtered_count = 0 # Counter for filtered SIDs (too short)
if results:
if verbose:
print_success(f"{len(results)} result(s) returned by query")
elif not debug_mode:
print_success(f"{len(results)} result(s) returned by query")
for row in results:
# Results can be dict or lists depending on version
if isinstance(row, dict):
# Dictionary format (like in NetExec)
# Keys can be lowercase, uppercase, or with spaces
name = row.get('name') or row.get('Name') or row.get('NAME') or 'N/A'
sid_hex = row.get('sidhex') or row.get('SIDHex') or row.get('SIDHEX') or row.get('sidhex') or ''
# Also try with empty keys (like in NetExec where some columns have empty key)
if not name or name == 'N/A':
# Find first non-empty value that could be the name
for key, value in row.items():
if key and value and key.lower() != 'sidhex':
name = str(value)
break
if not sid_hex:
# Find value that could be the SID hex
for key, value in row.items():
if value and (key.lower() in ['sidhex', 'sid'] or (isinstance(value, str) and len(str(value)) > 20)):
sid_hex = str(value)
break
else:
# List/tuple format (fallback)
if len(row) >= 2:
name = str(row[0]) if row[0] is not None else "N/A"
sid_hex = str(row[1]) if row[1] is not None else ""
else:
continue
# Debug for each line (only if verbose enabled)
if verbose:
print_info(f"Line: name='{name}', sid_hex='{sid_hex}' (length: {len(str(sid_hex))})")
# Clean SID hex (may contain spaces or 0x prefix)
if sid_hex:
sid_hex = str(sid_hex).strip()
# Filter valid SIDs (at least 8 bytes = 16 hex characters without 0x)
hex_length = len(sid_hex)
if sid_hex.startswith('0x') or sid_hex.startswith('0X'):
hex_length -= 2
if hex_length >= 16: # At least 8 bytes for a real Windows SID
sid_formatted = hex_to_sid(sid_hex)
if not sid_formatted.startswith("Error"):
sids_found.append((str(name), sid_hex, sid_formatted))
elif debug_mode:
print_warning(f"Debug: Conversion error for '{sid_hex}': {sid_formatted}")
else:
filtered_count += 1
if debug_mode:
print_info(f"Debug: SID hex too short (system role): '{sid_hex}' (length: {hex_length})")
# Informative message if results were filtered
if filtered_count > 0:
if verbose:
print_info(f"{filtered_count} result(s) filtered (system roles with SIDs too short)")
elif not debug_mode:
print_info(f"{filtered_count} result(s) filtered (system roles with SIDs too short)")
# Extract domain SID (base SID without final RID)
# Domain SIDs start with S-1-5-21- and have at least 3 RIDs after 21
domain_sid = None
for name, sid_hex, sid_formatted in sids_found:
if sid_formatted.startswith('S-1-5-21-'):
# Extract base SID (without last RID)
parts = sid_formatted.split('-')
if len(parts) >= 5: # S-1-5-21-xxx-xxx-xxx-RID
# Domain SID is S-1-5-21-xxx-xxx-xxx (without last RID)
domain_sid = '-'.join(parts[:-1])
break
# Perform RID brute force if requested (before disconnecting)
rid_entries = []
if rid_brute and domain_sid:
print_info("Starting RID brute force...")
rid_entries = rid_brute_force(mssql, domain_sid, max_rid, verbose)
# Add RID brute force results to sids_found
for entry in rid_entries:
sids_found.append((
entry['username'],
'', # No hex SID for RID brute force results
entry['full_sid']
))
if rid_entries:
print_success(f"RID brute force: {len(rid_entries)} entries found")
else:
print_warning("RID brute force: No entries found")
elif rid_brute and not domain_sid:
print_error("Domain SID not found. Cannot perform RID brute force.")
# Disconnect after RID brute force (if performed)
mssql.disconnect()
# Add domain SID to results if found
if domain_sid:
sids_found.append(('DOMAIN_SID', '', domain_sid))
return sids_found
except Exception as e:
print_error(f"Error during connection/retrieval: {str(e)}")
import traceback
traceback.print_exc()
sys.exit(1)
def main():
parser = argparse.ArgumentParser(
description="MSSQL hexadecimal SID converter to readable format (S-1-5-...)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""Examples:
# Convert a hexadecimal SID
python3 hex2sid.py 0x010500000000000515000000b9b39f9b3fa63e5ea8d050a1290a0000
# Convert from a file
python3 hex2sid.py -f hex_list.txt
# Direct retrieval from MSSQL
python3 hex2sid.py --mssql 192.168.1.100 -u sa -P Password123
python3 hex2sid.py --mssql 192.168.1.100 -u user -P pass -d DOMAIN
python3 hex2sid.py --mssql 192.168.1.100 -u user -H aad3b435b51404eeaad3b435b51404ee:...
"""
)
parser.add_argument("hex_string", nargs='?', help="Hexadecimal SID value (starting with 0x or not)")
parser.add_argument("-f", "--file", help="File containing a list of hexadecimal values (one per line)")
# Options for MSSQL connection
parser.add_argument("--mssql", metavar="HOST", help="Retrieve SIDs directly from an MSSQL server")
parser.add_argument("-P", "--port", type=int, default=1433, help="MSSQL server port (default: 1433)")
parser.add_argument("-u", "--username", help="Username for MSSQL authentication")
parser.add_argument("-p", "--password", help="Password for MSSQL authentication")
parser.add_argument("-d", "--domain", help="Windows domain (for Windows authentication)")
parser.add_argument("-H", "--hashes", help="NTLM hash in LM:NT format or NT only")
parser.add_argument("--no-windows-auth", action="store_true", help="Use SQL authentication instead of Windows")
parser.add_argument("-q", "--query", help="Custom SQL query (default: retrieves SIDs from sys.server_principals)")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose mode (shows more details)")
parser.add_argument("-o", "--output", help="Output file to save SIDs (format: name,sid_hex,formatted_sid)")
parser.add_argument("--rid-brute", type=int, metavar="MAX_RID", nargs='?', const=5000, help="Perform RID brute force up to MAX_RID (default: 5000). Requires domain SID to be found.")
args = parser.parse_args()
# Case 1: Retrieval from MSSQL
if args.mssql:
if not args.username:
print_error("--mssql option requires a username (-u)")
sys.exit(1)
password = args.password if args.password else ""
if not password and not args.hashes:
import getpass
password = getpass.getpass("Password: ")
# windows_auth=None means "auto" (try Windows by default)
# windows_auth=False means force SQL Server (if --no-windows-auth is specified)
windows_auth_param = None if not args.no_windows_auth else False
# Get max_rid for RID brute force
max_rid = args.rid_brute if args.rid_brute else 5000
sids = fetch_sids_from_mssql(
host=args.mssql,
port=args.port,
username=args.username,
password=password,
domain=args.domain,
hashes=args.hashes,
windows_auth=windows_auth_param,
query=args.query,
verbose=args.verbose,
rid_brute=args.rid_brute is not None,
max_rid=max_rid
)
if sids:
# Separate domain SID, RID brute force results, and other SIDs
domain_sid_entry = None
rid_brute_sids = [] # SIDs from RID brute force (no hex SID)
other_sids = []
for name, sid_hex, sid_formatted in sids:
if name == 'DOMAIN_SID':
domain_sid_entry = (name, sid_hex, sid_formatted)
elif not sid_hex and sid_formatted: # RID brute force results have no hex SID
# Extract RID from formatted SID (last part after -)
parts = sid_formatted.split('-')
if len(parts) > 0:
try:
rid = int(parts[-1])
rid_brute_sids.append((rid, name, sid_formatted))
except ValueError:
other_sids.append((name, sid_hex, sid_formatted))
else:
other_sids.append((name, sid_hex, sid_formatted))
else:
other_sids.append((name, sid_hex, sid_formatted))
# Display normal SIDs
if other_sids:
print_success(f"\n{len(other_sids)} SID(s) found:\n")
header = colored(f"{'Name':<30} {'SID Hex':<50} {'Formatted SID'}", "cyan", attrs=["bold"])
print(header)
print(colored("-" * 100, "cyan"))
for name, sid_hex, sid_formatted in other_sids:
# Color the formatted SID in green
formatted_colored = colored(sid_formatted, "green")
print(f"{name:<30} {sid_hex:<50} {formatted_colored}")
# Display RID brute force results (sorted by RID)
if rid_brute_sids:
rid_brute_sids.sort(key=lambda x: x[0]) # Sort by RID
print_success(f"\nRID brute force results ({len(rid_brute_sids)} entries):\n")
for rid, username, full_sid in rid_brute_sids:
# Color RID in cyan and username in green
rid_colored = colored(str(rid), "cyan", attrs=["bold"])
username_colored = colored(username, "green")
print(f" {rid_colored}: {username_colored}")
# Display domain SID in a special way
if domain_sid_entry:
print_success("\nDomain SID:")
domain_sid_colored = colored(domain_sid_entry[2], "yellow", attrs=["bold"])
print(f" {domain_sid_colored}")
# Save to output file if specified
if args.output:
try:
with open(args.output, 'w') as f:
# Write header
f.write("name,sid_hex,formatted_sid\n")
# Write all SIDs (including domain SID)
for name, sid_hex, sid_formatted in sids:
# Escape commas in name if present
name_escaped = name.replace(',', '\\,')
f.write(f"{name_escaped},{sid_hex},{sid_formatted}\n")
print_success(f"\nResults saved to: {args.output}")
except Exception as e:
print_error(f"Error writing to output file: {e}")
else:
print_warning("No SID found")
# Case 2: Read from file
elif args.file:
if not os.path.exists(args.file):
print_error(f"File '{args.file}' not found.")
sys.exit(1)
results = []
with open(args.file, 'r') as f:
for line in f:
h = line.strip()
if h:
converted = hex_to_sid(h)
print(f"{h} -> {converted}")
if not converted.startswith("Error"):
results.append(('', h, converted))
# Save to output file if specified
if args.output and results:
try:
with open(args.output, 'w') as f:
f.write("name,sid_hex,formatted_sid\n")
for name, sid_hex, sid_formatted in results:
f.write(f"{name},{sid_hex},{sid_formatted}\n")
print_success(f"\nResults saved to: {args.output}")
except Exception as e:
print_error(f"Error writing to output file: {e}")
# Case 3: Direct argument
elif args.hex_string:
converted = hex_to_sid(args.hex_string)
print(converted)
# Save to output file if specified
if args.output and not converted.startswith("Error"):
try:
with open(args.output, 'w') as f:
f.write("name,sid_hex,formatted_sid\n")
f.write(f",{args.hex_string},{converted}\n")
print_success(f"\nResult saved to: {args.output}")
except Exception as e:
print_error(f"Error writing to output file: {e}")
# Case 4: Nothing provided
else:
parser.print_help()
if __name__ == "__main__":
main()