0

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-

  • Does this answer your question? [Howto determine file owner on windows using python without pywin32](https://stackoverflow.com/questions/8086412/howto-determine-file-owner-on-windows-using-python-without-pywin32) – Szabolcs Feb 07 '22 at 11:57

2 Answers2

0
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)
tomerar
  • 805
  • 5
  • 10
0

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 = win32security.GetFileSecurity(file, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner()
name, domain, type = win32security.LookupAccountSid(None, owner_sid)
print(name)
Wendel
  • 1
  • 1