2009-12-02 17 views
19

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

のような関数は次のようになります。所有者のUIDを取得するために、使用の

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) 

例:あなたはos.stat()を使用したい

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

答えて

48

私はPythonの男の本当に多くないんだけど、私はこれをかき立てることができました:

from os import stat 
from pwd import getpwuid 

def find_owner(filename): 
    return getpwuid(stat(filename).st_uid).pw_name 
14

from os import stat 
stat(my_filename).st_uid 

ただしを、そのstatは、実際のユーザー名ではなく、ユーザーID番号(たとえば、rootの場合は0)を返します。

3

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

3

ここでは、ファイルの所有者を見つけることができるかを示す、いくつかのサンプルコードです:

#!/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 
2

私は、所有者ユーザーとグループ情報を取得するために探して、最近、この全体でつまずいたので、私は、私は私が思いついたものを共有したいと思った:

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 
    ) 
関連する問題