views:

339

answers:

4

I need a function or method in Python to find the owner of a file or directory?

the function should be link

find_owner("/home/somedir/somefile")

owner3

+5  A: 

You want "os":

http://docs.python.org/library/os.html

os.stat(path)

Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user id of owner), st_gid (group id of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):

Kurt
+2  A: 

See os.stat. It gives you st_uid which is the user ID of the owner. Then you have to convert it to the name. To do that, use pwd.getpwuid.

Craig McQueen
+7  A: 

I'm not really much of a python guy, but I was able to whip this up:

from os import stat
from pwd import getpwuid

def find_owner(file):
    return getpwuid(stat(file).st_uid).pw_name
asveikau
+1  A: 

Here is some example code, showing how you can find the owner of file:

#!/usr/bin/env python
import os
import pwd
filename='/etc/passwd'
st=os.stat(filename)
uid=st[stat.ST_UID]
print(uid)
# 0
userinfo=pwd.getpwuid(st.st_uid)
print(userinfo)
# pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')
ownername=pwd.getpwuid(st.st_uid).pw_name
print(ownername)
# root
unutbu