/proc/net/tcp为我提供了套接字的本地地址、端口和inode编号(例如,0.0.0.0:5432和9289 )。
根据上面的信息,我想查找特定进程的PID。
可以在/proc中打开每个编号的文件夹,然后使用类似于"$ sudo ls -l /proc/*/fd/ 2>/dev/null | grep socket“这样的外壳命令检查符号链接以查找匹配的套接字/inode编号。然而,这似乎比必要的计算成本更高,因为任何给定系统上的进程中都有<5%的进程具有开放的TCP套接字。
找到已打开给定套接字的PID的最有效方法是什么?我更喜欢使用标准库,目前我正在使用Python 3.2.3进行开发。
编辑:从问题中删除了代码示例,因为它们现在包含在下面的答案中。
发布于 2013-02-04 03:52:40
下面的代码实现了最初的目标:
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
发布于 2013-02-03 07:29:29
我不知道如何在python中做到这一点,但您可以使用lsof(1)
lsof -i | awk -v sock=158384387 '$6 == sock{print $2}'
158384387
是套接字的inode。然后使用subprocess.Popen
从python中调用它。
如果想要查看其他用户打开的套接字,则必须使用sudo(8)。
https://stackoverflow.com/questions/14667215
复制相似问题