View Windows file metadata in Python

I am writing a script to email the owner of a file when a separate process has finished. I have tried:

import os
FileInfo = os.stat("test.txt")
print (FileInfo.st_uid)

The output of this is the owner ID number. What I need is the Windows user name.

13.10.2009 17:46:06
I thought FileInfo.st_uid always returned 0 under windows?
Mark 13.10.2009 17:55:22
2 ОТВЕТА

I think the only chance you have is to use the pywin32 extensions and ask windows yourself.

Basically you look on msdn how to do it in c++ and use the according pywin32 functions.

from win32security import GetSecurityInfo, LookupAccountSid
from win32security import OWNER_SECURITY_INFORMATION, SE_FILE_OBJECT

from win32file import CreateFile
from win32file import GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL

fh = CreateFile( __file__, GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None )
info = GetSecurityInfo( fh, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION )

name, domain, type_id = LookupAccountSid( None, info.GetSecurityDescriptorOwner() )
print name, domain, type_id
2
13.10.2009 18:41:22
РЕШЕНИЕ

Once I stopped searching for file meta data and started looking for file security I found exactly what I was looking for.

import tempfile
import win32api
import win32con
import win32security

f = tempfile.NamedTemporaryFile ()
FILENAME = f.name
try:
  sd = win32security.GetFileSecurity (FILENAME,win32security.OWNER_SECURITY_INFORMATION)
  owner_sid = sd.GetSecurityDescriptorOwner ()
  name, domain, type = win32security.LookupAccountSid (None, owner_sid)

  print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
  print "File owned by %s\\%s" % (domain, name)
finally:
  f.close ()

Mercilessly ganked from http://timgolden.me.uk/python-on-windows/programming-areas/security/ownership.html

3
13.10.2009 18:37:45