stib
stib

Reputation: 3512

cross-platform method for determining file owner in Python

I need to find the owner of files in a script running on Windows, Linux and Mac. os.stat returns the owner id, but on windows I can't use getpwuid to find the actual name of the owner. I need the name as a string.

Upvotes: 1

Views: 376

Answers (1)

zom-pro
zom-pro

Reputation: 1649

It seems like you won't find a silver bullet (cross platform). For windows you can use the win32 module like shown here

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)

Upvotes: 1

Related Questions