43

ファイルまたはディレクトリの所有者を見つけるには、Pythonの関数またはメソッドが必要です。

関数は次のようになります。

>>> find_owner("/home/somedir/somefile")
owner3
4

7 に答える 7

87

私はPythonの人ではありませんが、これを作成することができました。

from os import stat
from pwd import getpwuid

def find_owner(filename):
    return getpwuid(stat(filename).st_uid).pw_name
于 2009-12-02T04:27:09.280 に答える
20

あなたが使いたい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番号(たとえば、rootの場合は0)が返されることに注意してください。

于 2009-12-02T04:25:33.270 に答える
17

これは古い質問ですが、Python3を使用したより簡単なソリューションを探している人にとっては。

次のように'sとメソッドを呼び出すことにより、 Pathfromを使用しpathlibてこの問題を解決することもできます。Pathownergroup

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()}"
于 2020-04-01T05:53:01.687 に答える
7

私は最近、所有者のユーザーとグループの情報を取得しようとしてこれに遭遇したので、私が思いついたものを共有したいと思いました:

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
    )
于 2016-08-06T01:51:35.247 に答える
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
于 2009-12-02T04:29:04.093 に答える
3

os.statを参照してください。st_uid所有者のユーザーIDを教えてくれます。次に、それを名前に変換する必要があります。これを行うには、pwd.getpwuidを使用します。

于 2009-12-02T04:26:06.953 に答える
0

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'))
于 2020-01-15T18:44:08.737 に答える