4

/proc/net/tcp は、ソケットのローカル アドレス、ポート、および inode 番号 (たとえば、0.0.0.0:5432 および 9289) を提供します。

上記の情報を考慮して、特定のプロセスの PID を見つけたいと思います。

/proc 内のすべての番号付きフォルダーを開き、"$ sudo ls -l /proc/*/fd/ 2>/dev/null | grep socket" のようなシェル コマンドを使用して、一致するソケット/i ノード番号についてシンボリック リンクをチェックすることができます。ただし、特定のシステムのプロセスの 5% 未満が TCP ソケットを開いているため、これは必要以上に計算コストがかかるようです。

特定のソケットを開いた PID を見つける最も効率的な方法は何ですか? 私は標準ライブラリを使用したいと思っており、現在 Python 3.2.3 で開発しています。

編集:以下の回答にコード サンプルが含まれるようになったため、質問からコード サンプルを削除しました。

4

2 に答える 2

5

次のコードは、元の目的を達成します。

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-03T19:52:39.620 に答える
2

Pythonでこれを行う方法はわかりませんが、次を使用できますlsof(1)

lsof -i | awk -v sock=158384387 '$6 == sock{print $2}'

158384387ソケットのiノードです。そして、を使用してPythonから呼び出しますsubprocess.Popen

他のユーザーによって開かれたソケットを確認するには、sudo(8)を使用する必要があります。

于 2013-02-02T23:29:28.670 に答える