先安裝 python3.5, 再安裝 pywin32-227.win32-py3.5.exe (對應32位 python)或 pywin32-227.win-amd64-py3.5.exe(對應64位 python)
獲得 文件 的 所有者,運行:
import win32api
import win32con
import win32security
# 獲得登陸用戶的名字
print "I am", win32api.GetUserNameEx(win32con.NameSamCompatible)
FILENAME = "temp.txt"
open(FILENAME, "r").close() # 這裏要寫 "r",不能寫 "w"
sd = win32security.GetFileSecurity(FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner()
name, domain, type = win32security.LookupAccountSid(None, owner_sid)
print "File owned by %s\\%s" % (domain, name)
打印結果:
I am 當前登陸用戶名\當前登陸用戶名
File owned by 文件的所有者所屬的域\文件的所有者的用戶名
獲取 文件夾 的 所有者,運行:
import win32api
import win32con
import win32security
FILENAME = "d:\\test"
sd = win32security.GetFileSecurity(FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner()
name, domain, type = win32security.LookupAccountSid(None, owner_sid)
print "Dir owned by %s\\%s" % (domain, name)
打印結果:
Dir owned by 文件夾的所有者所屬的域\文件夾的所有者的用戶名
-----------------------------------------------------------------------------
其他參考:
各個版本 pywin32 的下載地址: https://github.com/mhammond/pywin32/releases
解決在Python中使用Win32api報錯的問題,No module named win32api: https://www.cnblogs.com/SH170706/p/9640110.html
這段 python 程序的英語說明: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html