我需要从 python 脚本获取当前登录用户的 SID。一种选择是在 shell 到命令提示符命令 whoami /user 时读取返回文本。但这真的很难看。当然一定有更好的方法吗?
在 Mehrdad 在他的评论中提到的 programcreek 网站上四处查看后
我想出了这个
# 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)
可能需要一些调整,因为我只是获取拥有当前目录的用户。
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())
使用
sidstr = win32security.ConvertSidToStringSid(sid)
方法更改它。
我认为获取当前进程的用户是更理想的。 (我仅将我的系统用作一个用户,因此我确信第一个适用于许多用例)
这是我在 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
这是我使用
whoami
windows shell 命令的示例,无需安装 win32security
模块。
import subprocess
cmd = 'whoami /User'
output = subprocess.check_output(cmd)
sid = output.decode().split('\r\n')[6].split(' '*4)[1]
print(sid)
甚至更短
import subprocess
sid = subprocess.check_output('whoami /User').decode().split('\r\n')[6].split(' '*4)[1]
它从
whoami
命令的文本输出中提取 SID 字符串。这是针对 python 3 和 windows 10 的,如果 Microsoft 在不同的 Windows 版本中更改了 whoami
的输出,则可能会中断。