我想在Linux上的Python一個進程ID獲得用戶名,所以我可以告訴它:如何從Linux中的python中的進程ID獲取用戶名?
name user name pid
Chrome wong2 123
我想在Linux上的Python一個進程ID獲得用戶名,所以我可以告訴它:如何從Linux中的python中的進程ID獲取用戶名?
name user name pid
Chrome wong2 123
您可以從/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內核中。)
在Linux中,你可以做ps -f
,你會得到的UID和PID(-f
做全格式列表)。
你可以使用subprocess.Popen來調用一個shell命令,並從標準輸出到一個可變的讀取。
import subprocess
p=Popen(['/bin/ps', '-o', 'comm,pid,user',stdout=PIPE)
text=p.stdout.read()
如果你不想來解析在/ 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]