我需要Python中的函數或方法來查找文件或目錄的所有者。如何在Python中找到文件或目錄的所有者
的功能應該是這樣的:
>>> find_owner("/home/somedir/somefile")
owner3
我需要Python中的函數或方法來查找文件或目錄的所有者。如何在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
返回用戶標識號(例如,0代表根),而不是實際的用戶名。
請參閱os.stat。它給你st_uid
這是所有者的用戶ID。然後你必須將其轉換爲名稱。要做到這一點,請使用pwd.getpwuid。
下面是一些示例代碼,顯示你如何能找到文件的所有者:
#!/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
我碰到這個偶然最近,希望得到所有人的用戶和組信息,所以我想我會分享我想出了:
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
)