如何在python中找到文件或目录的所有者

ram*_*daz 31 python linux permissions file ownership

我需要Python中的函数或方法来查找文件或目录的所有者.

功能应该是:

>>> find_owner("/home/somedir/somefile")
owner3
Run Code Online (Sandbox Code Playgroud)

asv*_*kau 63

我不是一个蟒蛇人,但我能够鞭打它:

from os import stat
from pwd import getpwuid

def find_owner(filename):
    return getpwuid(stat(filename).st_uid).pw_name
Run Code Online (Sandbox Code Playgroud)


Kur*_*urt 15

你想用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)
Run Code Online (Sandbox Code Playgroud)

获取所有者UID的用法示例:

from os import stat
stat(my_filename).st_uid
Run Code Online (Sandbox Code Playgroud)

但是,请注意,stat返回用户标识号(例如,0表示root用户),而不是实际用户名.


Gáb*_*bor 12

这是一个老问题,但对于那些正在寻找更简单的 Python 3 解决方案的人来说。

您也可以使用Pathfrompathlib来解决这个问题,方法是像这样调用Path'sownergroup方法:

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}")
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下,方法可能如下:

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()}"
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 5

下面是一些示例代码,展示了如何找到文件的所有者:

#!/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
Run Code Online (Sandbox Code Playgroud)


Wil*_*ill 5

我最近偶然发现了这个问题,希望获得所有者用户和组信息,所以我想分享一下我的想法:

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
    )
Run Code Online (Sandbox Code Playgroud)