我需要 Python 中的函数或方法来查找文件或目录的所有者。
函数应该是这样的:
>>> find_owner("/home/somedir/somefile")
owner3
我需要 Python 中的函数或方法来查找文件或目录的所有者。
函数应该是这样的:
>>> find_owner("/home/somedir/somefile")
owner3
我不是一个真正的蟒蛇人,但我能够做到这一点:
from os import stat
from pwd import getpwuid
def find_owner(filename):
return getpwuid(stat(filename).st_uid).pw_name
你想使用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)
获取所有者 UID 的用法示例:
from os import stat
stat(my_filename).st_uid
但是请注意,它stat
返回的是用户 ID 号(例如,0 代表 root),而不是实际的用户名。
这是一个老问题,但对于那些正在寻找更简单的 Python 3 解决方案的人来说。
你也可以使用Path
frompathlib
来解决这个问题,通过调用Path
'sowner
和group
这样的方法:
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}")
所以在这种情况下,方法可能如下:
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()}"
我最近偶然发现了这个,希望获得所有者用户和组信息,所以我想我会分享我的想法:
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
)
下面是一些示例代码,展示了如何找到文件的所有者:
#!/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
请参阅os.stat。它为您提供st_uid
所有者的用户 ID。然后,您必须将其转换为名称。为此,请使用pwd.getpwuid。
在 Windows 上这可以工作,但使用 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'))