在Python 3中查找给定套接字和inode的进程ID [英] Finding a process ID given a socket and inode in Python 3
问题描述
/proc/net/tcp为我提供了套接字的本地地址,端口和索引节点号(例如0.0.0.0:5432和9289).
/proc/net/tcp gives me a local address, port, and inode number for a socket (0.0.0.0:5432 and 9289, for example).
鉴于上述信息,我想查找特定过程的PID.
I'd like to find the PID for a specific process, given the above information.
可以打开/proc中的每个编号文件夹,然后使用诸如"$ sudo ls -l/proc/*/fd/2>/dev/null | grep"之类的shell命令检查符号链接中是否有匹配的套接字/索引号.插座".但是,这似乎比所需的计算更为昂贵,因为在任何给定系统上,少于5%的进程具有开放的TCP套接字.
It's possible to open every numbered folder in /proc, and then check symlinks for matching socket/inode numbers with a shell command like "$ sudo ls -l /proc/*/fd/ 2>/dev/null | grep socket". However, this seems more computationally expensive than necessary, since <5% of the processes on any given system have open TCP sockets.
查找已打开给定套接字的PID的最有效方法是什么?我更喜欢使用标准库,并且目前正在使用Python 3.2.3进行开发.
What's the most efficient way to find the PID which has opened a given socket? I'd prefer to use standard libraries, and I'm currently developing with Python 3.2.3.
编辑:由于现在已包含在下面的答案中,因此从问题中删除了代码示例.
Removed the code samples from the question, since they are now included in the answer below.
推荐答案
以下代码实现了原始目标:
The following code accomplishes the original goal:
def find_pid(inode):
# get a list of all files and directories in /proc
procFiles = os.listdir("/proc/")
# remove the pid of the current python process
procFiles.remove(str(os.getpid()))
# set up a list object to store valid pids
pids = []
for f in procFiles:
try:
# convert the filename to an integer and back, saving the result to a list
integer = int(f)
pids.append(str(integer))
except ValueError:
# if the filename doesn't convert to an integer, it's not a pid, and we don't care about it
pass
for pid in pids:
# check the fd directory for socket information
fds = os.listdir("/proc/%s/fd/" % pid)
for fd in fds:
# save the pid for sockets matching our inode
if ('socket:[%d]' % inode) == os.readlink("/proc/%s/fd/%s" % (pid, fd)):
return pid
这篇关于在Python 3中查找给定套接字和inode的进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!