首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python 3中查找给定套接字和索引节点的进程ID

在Python 3中查找给定套接字和索引节点的进程ID
EN

Stack Overflow用户
提问于 2013-02-03 06:30:56
回答 2查看 8K关注 0票数 3

/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进行开发。

编辑:从问题中删除了代码示例,因为它们现在包含在下面的答案中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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
票数 5
EN

Stack Overflow用户

发布于 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)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14667215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档