Created
April 2, 2022 00:16
-
-
Save pljoel/4cbcfa93f7a8e702ac7b6056a84779a5 to your computer and use it in GitHub Desktop.
Get Windows Domain SID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
def get_domain_sid(domain_name: str) -> str: | |
# Reference: https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.securityidentifier | |
domain_component = [f"dc={dc}" for dc in domain_name.split(sep='.')] if domain_name else [] | |
domain_component = ",".join(domain_component) | |
domain_dn = f"LDAP://{domain_component}" | |
domain_sid_binary = f"([ADSI]\"{domain_dn}\").objectSid.Value" | |
cmd_domain_sid = f"[System.Security.Principal.SecurityIdentifier]::new({domain_sid_binary}, 0).Value" | |
# Execute powershell command to retrieve the domain sid | |
process_domain_sid = subprocess.run(["powershell", "-Command", cmd_domain_sid], capture_output=True, text=True) | |
if process_domain_sid.returncode != 0 or not process_domain_sid.stdout: | |
raise RuntimeError(f"Unable to get the Domain SID for {domain_name}") | |
domain_sid = process_domain_sid.stdout.strip() | |
print(f"Domain SID for {domain_name}: {domain_sid}") | |
return domain_sid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment