0

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.

1
  • I thought FileInfo.st_uid always returned 0 under windows? Commented Oct 13, 2009 at 17:55

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.