how to find the owner of a file or directory in python
Asked Answered
N

7

50

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

The function should be like:

>>> find_owner("/home/somedir/somefile")
owner3
Northerly answered 2/12, 2009 at 4:19 Comment(0)
P
94

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(filename):
    return getpwuid(stat(filename).st_uid).pw_name
Piquet answered 2/12, 2009 at 4:27 Comment(3)
Note that os.stat() doesn't work with symlinks by default. To stat symlinks, you need to pass the follow_symlinks=False param.Retribution
Is this solution Unix-only?Sleazy
Yes, it's Unix-only (it's not supported on Windows)Edvard
L
33

It's an old question, but for those who are looking for a simpler solution with Python 3.

You can also use Path from pathlib to solve this problem, by calling the Path's owner and group method like this:

from pathlib import Path

path = Path("/path/to/your/file")
owner = path.owner()
group = path.group()
print(f"{path.name} is owned by {owner}:{group}")

So in this case, the method could be the following:

from typing import Union
from pathlib import Path

def find_owner(path: Union[str, Path]) -> str:
    path = Path(path)
    return f"{path.owner()}:{path.group()}"
Lopsided answered 1/4, 2020 at 5:53 Comment(2)
says: NotImplementedError: Path.owner() is unsupported on this systemGarrettgarrick
@SemihSARI based on bugs.python.org/issue46733 it seems that owner and group "unconditionally raise NotImplementedError on Windows, since the pwd and grp modules are not available on Windows". I have no windows to come up with a proper help for you, but probably this is the way to get the info for windows: timgolden.me.uk/python/win32_how_do_i/…Skimmia
E
23

You want to use os.stat():

os.stat(path)
 Perform the equivalent of a stat() system call on the given path. 
 (This function follows symlinks; to stat a symlink use lstat().)

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)

Example of usage to get owner UID:

from os import stat
stat(my_filename).st_uid

Note, however, that stat returns user id number (for example, 0 for root), not actual user name.

Egesta answered 2/12, 2009 at 4:25 Comment(0)
A
11

I stumbled across this recently, looking to get owner user and group information, so I thought I'd share what I came up with:

import os
from pwd import getpwuid
from grp import getgrgid

def get_file_ownership(filename):
    return (
        getpwuid(os.stat(filename).st_uid).pw_name,
        getgrgid(os.stat(filename).st_gid).gr_name
    )
Anastos answered 6/8, 2016 at 1:51 Comment(0)
P
5

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.st_uid
print(uid)
# output: 0
userinfo = pwd.getpwuid(st.st_uid)
print(userinfo)
# output: 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)
# output: root
Phosphocreatine answered 2/12, 2009 at 4:29 Comment(0)
C
3

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.

Croup answered 2/12, 2009 at 4:26 Comment(0)
S
1

On Windows this Works but uses the cli

import os
from subprocess import Popen, PIPE
from collections import namedtuple


def sliceit(iterable, tup):
    return iterable[tup[0]:tup[1]].strip()

def convert_cat(line):
    # Column Align Text indicies from cmd
    # Date time dir filesize owner filename
    Stat = namedtuple('Stat', 'date time directory size owner filename')
    stat_index = Stat(date=(0, 11), 
                      time=(11, 18), 
                      directory=(18, 27), 
                      size=(27, 35), 
                      owner=(35, 59), 
                      filename=(59, -1))

    stat = Stat(date=sliceit(line, stat_index.date),
                      time=sliceit(line, stat_index.time),
                      directory=sliceit(line, stat_index.directory),
                      size=sliceit(line, stat_index.size),
                      owner=sliceit(line, stat_index.owner),
                      filename=sliceit(line, stat_index.filename))
    return stat

def stat(path):
    if not os.path.isdir(path):
        dirname, filename = os.path.split(path)
    else:
        dirname = path
    cmd = ["cmd", "/c", "dir", dirname, "/q"]
    session = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    # cp1252 is common on my Norwegian Computer,
    # check encoding from your windows system
    result = session.communicate()[0].decode('cp1252')

    if os.path.isdir(path):
        line = result.splitlines()[5]
        return convert_cat(line)
    else:
        for line in result.splitlines()[5:]:
            if filename in line:
                return convert_cat(line)
        else:
            raise Exception('Could not locate file')

if __name__ == '__main__':
    print(stat('C:\\temp').owner)
    print(stat('C:\\temp\\diff.py'))
Stomatal answered 15/1, 2020 at 18:44 Comment(1)
the perfect copy pastaHardtack

© 2022 - 2024 — McMap. All rights reserved.