2009-12-02 20 views
19

में एक फ़ाइल या निर्देशिका के मालिक को खोजने के लिए मैं अजगर में एक समारोह या विधि जरूरत है एक फ़ाइल या निर्देशिका के मालिक को खोजने के लिए।कैसे अजगर

समारोह होना चाहिए की तरह:

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) 

उपयोग के उदाहरण मालिक यूआईडी पाने के लिए:

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

उत्तर

48

मैं एक अजगर पुरुष की वास्तव में बहुत है, लेकिन मैं इस कोड़ा करने में सक्षम था नहीं कर रहा हूँ:

from os import stat 
from pwd import getpwuid 

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

आप os.stat() उपयोग करना चाहते हैं

from os import stat 
stat(my_filename).st_uid 

हालांकि, ध्यान दें कि stat उपयोगकर्ता आईडी संख्या (उदाहरण के लिए, रूट के लिए 0) देता है, वास्तविक उपयोगकर्ता नाम नहीं।

3

os.stat देखें। यह आपको 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 
    )