2011-03-16 56 views

回答

9

您可以從/proc/pid/status中閱讀uid(s)。他們排在以Uid:開頭的行中。從uid中,您可以使用pwd.getpwuid(pid).pw_name來獲取用戶名。

UID = 1 
EUID = 2 

def owner(pid): 
    '''Return username of UID of process pid''' 
    for ln in open('/proc/%d/status' % pid): 
     if ln.startswith('Uid:'): 
      uid = int(ln.split()[UID]) 
      return pwd.getpwuid(uid).pw_name 

(常量從fs/proc/array.c導出在Linux內核中。)

0

在Linux中,你可以做ps -f,你會得到的UID和PID(-f做全格式列表)。

1

你可以使用subprocess.Popen來調用一個shell命令,並從標準輸出到一個可變的讀取。

python subprocess

import subprocess 
p=Popen(['/bin/ps', '-o', 'comm,pid,user',stdout=PIPE) 
text=p.stdout.read() 
4

如果你不想來解析在/ proc/PID/status文件和進程沒有改變UID,如果把一個進程似乎昂貴查找用戶名,然後嘗試:

import os 
import pwd 
# the /proc/PID is owned by process creator 
proc_stat_file = os.stat("/proc/%d" % pid) 
# get UID via stat call 
uid = proc_stat_file.st_uid 
# look up the username from uid 
username = pwd.getpwuid(uid)[0] 
相關問題