chinguetti
chinguetti

Reputation: 128

In python how can I get current users SID in Windows?

I need to get the SID of the currently logged on user from a python script. One option is to read the return text when shelling to a command prompt command whoami /user. But this is really ugly. Surely there must be a better way?

Upvotes: 2

Views: 3967

Answers (3)

Patrick
Patrick

Reputation: 141

here is my example by using the whoami windows shell command without the need of installing the win32security module. I don't believe it looks more ugly than the other solutions ...

import subprocess
    
cmd = 'whoami /User'
output = subprocess.check_output(cmd)
sid = output.decode().split('\r\n')[6].split(' '*4)[1]
print(sid)
  • it splits the output of the whoami shell command by lines
  • takes the 7th line, splits it at 4 spaces and gets SID string

or even shorter

import subprocess    
sid = subprocess.check_output('whoami /User').decode().split('\r\n')[6].split(' '*4)[1]

this is for python 3 and windows 10 and may break if Microsoft changed the output of whoami in different Windows versions.

Upvotes: 1

RixTheTyrunt
RixTheTyrunt

Reputation: 406

Here's an my example of doing so in Python:

import subprocess
import os

sid = None
out = subprocess.Popen("wmic useraccount get name, sid", stdout=subprocess.PIPE)
out = out.communicate()[0].decode().replace("\r", "")
for line in out.split("\n"):
    if line.startswith(os.getlogin()):
        sid = line.replace(os.getlogin(), "").strip()
        break

Upvotes: 3

Phani Rithvij
Phani Rithvij

Reputation: 4477

After looking around in the programcreek site that Mehrdad mentioned in his comment

I came up with this

# pip install pywin32
import win32security

desc = win32security.GetFileSecurity(
    ".", win32security.OWNER_SECURITY_INFORMATION
)
sid = desc.GetSecurityDescriptorOwner()

# https://www.programcreek.com/python/example/71691/win32security.ConvertSidToStringSid
sidstr = win32security.ConvertSidToStringSid(sid)
print("Sid is", sidstr)

Might need some tweaking because I'm just getting the user who owns the current directory.

There's this example on the pywin32 github

from ntsecuritycon import *
import win32api, win32security, winerror

# This is a Python implementation of win32api.GetDomainName()
def GetDomainName():
    try:
        tok = win32security.OpenThreadToken(win32api.GetCurrentThread(),
                                            TOKEN_QUERY, 1)
    except win32api.error as details:
        if details[0] != winerror.ERROR_NO_TOKEN:
            raise
        # attempt to open the process token, since no thread token
        # exists
        tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                             TOKEN_QUERY)
    sid, attr = win32security.GetTokenInformation(tok, TokenUser)
    win32api.CloseHandle(tok)

    name, dom, typ = win32security.LookupAccountSid(None, sid)
    return dom

if __name__=='__main__':
    print("Domain name is", GetDomainName())

Change it by using the sidstr = win32security.ConvertSidToStringSid(sid) method.

It's getting the current process's user which is more ideal I think. (I use my system as only one user so I'm sure the first one works for many use cases)

Upvotes: 3

Related Questions