'Get owner of a file using python on windows system
I want to extract the owner of a file within a python3 script on a Windows system.
When I run: os.path.expanduser(fp)
or
os.stat(fp).st_uid
I receive a 0 for all my discussed files.
Does anybody know how to extract the id or name of an owner of a file using python on windows.
Thanks -d-
Solution 1:[1]
import win32api
import win32con
import win32security
FILENAME = "temp.txt"
open (FILENAME, "w").close ()
print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
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)
Solution 2:[2]
You need to install pywin32 package:
$ pip install pywin32
and for fetching the id or name of an owner of a file you can use below code:
import win32security
sd = in32security.GetFileSecurity(file, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner()
name, domain, type = win32security.LookupAccountSid(None, owner_sid)
print(name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tomerar |
| Solution 2 | Javad Nikbakht |
