Last active
April 2, 2022 02:22
-
-
Save pljoel/a1c46d92e832e5cbb991f1b732a30156 to your computer and use it in GitHub Desktop.
Get Windows User or Group 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_user_group_sids(username: str, only_rid: bool = False) -> list: | |
# Reference: https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity | |
# Only retrieve the domain SIDs | |
cmd_user_group_sids = f"([System.Security.Principal.WindowsIdentity]::new(\"{username}\").Groups | Where AccountDomainSid).Value" | |
process_user_group_sids = subprocess.run(["powershell", "-Command", cmd_user_group_sids], capture_output=True, text=True) | |
if process_user_group_sids.returncode != 0 or not process_user_group_sids.stdout: | |
raise RuntimeError(f"Unable to get group SIDs for {username}") | |
group_sids = process_user_group_sids.stdout.strip().split('\n') | |
print(f"Group SIDs for {username}: {group_sids}") | |
if only_rid: | |
group_rids = [sid.split(sep='-')[-1] for sid in group_sids] | |
print(f"Relative group IDs for {username}: {group_rids}") | |
return group_rids | |
return group_sids |
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_user_or_group_sid(name: str, only_rid: bool = False) -> str: | |
# References: | |
# - https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.ntaccount | |
# - https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.securityidentifier | |
cmd_sid = f"[System.Security.Principal.NTAccount]::new(\"{name}\").Translate([System.Security.Principal.SecurityIdentifier]).Value " | |
process_sid = subprocess.run(["powershell", "-Command", cmd_sid], capture_output=True, text=True) | |
if process_sid.returncode != 0 or not process_sid.stdout: | |
raise RuntimeError(f"Unable to get SID for {name}") | |
sid = process_sid.stdout.strip() | |
print(f"SID for {name}: {sid}") | |
if only_rid: | |
rid = sid.split(sep='-')[-1] | |
print(f"Relative ID for {name}: {rid}") | |
return rid | |
return sid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment