Get the owner of a file

Introduction

The requirement: to determine who owns a file

The Code

This uses the Windows security API which isn't the easiest thing in the world to come to grips with. In this case, however, it's not too bad. We'll get the file's security descriptor, pull out of that the field which refers to the owner and then translate that from the ubitquitous-but-impenetrable SID to a user name.

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)