在 python 中,是否有跨平台的方法来确定哪个进程正在侦听给定端口?

发布于 2024-09-26 12:35:04 字数 706 浏览 0 评论 0原文

在 Linux 中,我可以使用 lsof -i ,如以下函数所示:

def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid

是否有跨平台的方法来解决这个问题?

作为相关参考,一旦我知道进程 id,psutil 库就非常好,可以让我以跨平台的方式为其确定各种有用的流程信息。我现在无法让第一部分跨平台工作(查找 pid)。


如果不熟悉 lsof -i 开关,输出如下所示(启动一个打开 TCP 套接字侦听端口 1234 的 Python 进程后):

$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)

In linux, I can use lsof -i as in the following function:

def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid

Is there a cross-platform way to figure this out?

As a relevant reference, once I know the process id, the psutil library is very nice and lets me determine all sorts of useful process information for it in a cross-platform way. I just can't get the first part to work (finding the pid) cross-platform at the moment.


If not familiar with the lsof -i switch, the output looks like below (after launching a python process that opens a TCP socket listening on port 1234):

$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橘虞初梦 2024-10-03 12:35:04

这个答案与您的问题更相关,但是如果您可以找到特定于操作系统的方法,但没有严格可移植的方法,那么我会让您的模块如下所示

def find_port_owner_windows(p):
    doit()

def find_port_owner_linux(p):
    doit2()

port_finders = {'nt': find_port_owner_windows,
                'posix': find_port_owner_linux}

try:
    find_port_owner = port_finders[os.name]
except KeyError:
    raise RuntimeError("No known port finder for your OS (%s)" % os.name)

This answer is more of a tangent to your question, but if you can find OS-specific ways but nothing strictly portable, I'd make your module like the following

def find_port_owner_windows(p):
    doit()

def find_port_owner_linux(p):
    doit2()

port_finders = {'nt': find_port_owner_windows,
                'posix': find_port_owner_linux}

try:
    find_port_owner = port_finders[os.name]
except KeyError:
    raise RuntimeError("No known port finder for your OS (%s)" % os.name)
与之呼应 2024-10-03 12:35:04

不,这不是内置于 python 中的。

No, this is not built into python.

小忆控 2024-10-03 12:35:04

就像 Daenyth 的回答,这并不能准确回答您提出的问题,但我认为您可能会发现它很有帮助,因为答案似乎是“您不能”。

好吧,NT 的 netstat.exe 可能没有那么强大,但它至少可以做到这一点:

C:\Documents and Settings\Sam\My Documents>netstat -o -b -n

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    127.0.0.1:1083         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1084         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1085         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1214         127.0.0.1:9481         ESTABLISHED     236
  Can not obtain ownership information
  TCP    127.0.0.1:1231         127.0.0.1:31416        ESTABLISHED     2764
  [boincmgr.exe]

  TCP    127.0.0.1:3814         127.0.0.1:6000         ESTABLISHED     716
  [putty.exe]

“无法获取所有权信息”行是因为我没有以管理员身份运行它,所以(就像在 Linux 上一样)我实际上只能看到我自己的进程的此信息。 (实际上,我可能可以对 ACL 授予我必要访问权限的任何进程执行此操作,但实际上,这对于非管理员用户来说基本上与“我的进程”相同。)

netstat 的确切版本从资源管理器的“属性”对话框复制的 .exe 为“5.1.2600.5512 (xpsp.080413-0852)”。我碰巧运行的是 XP SP3,但我不确定该文件上次更新是什么时候。 (是的,我在 XP 中使用非管理员帐户。这并不像应有的那么容易,但也没有您想象的那么难。)

Like Daenyth's anwer, this doesn't precisely answer the question you asked, but I think you'll probably find it helpful given that the answer to that seems to be "you can't".

Well, NT's netstat.exe may not be quite as capable as that, but it can at least do this:

C:\Documents and Settings\Sam\My Documents>netstat -o -b -n

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    127.0.0.1:1083         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1084         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1085         127.0.0.1:6000         ESTABLISHED     3716
  [Xming.exe]

  TCP    127.0.0.1:1214         127.0.0.1:9481         ESTABLISHED     236
  Can not obtain ownership information
  TCP    127.0.0.1:1231         127.0.0.1:31416        ESTABLISHED     2764
  [boincmgr.exe]

  TCP    127.0.0.1:3814         127.0.0.1:6000         ESTABLISHED     716
  [putty.exe]

The "Can not obtain ownership information" lines are because I'm not running this as an administrator, so (just like on Linux) I can really only see this info for my own processes. (I'm probably actually allowed to do this for any process whose ACL grants me the necessary access, but in practice that means basically the same thing as "my processes" for non-admin users.)

The exact version of netstat.exe, as copied from Explorer's Properties dialog, is "5.1.2600.5512 (xpsp.080413-0852)". I happen to be running XP SP3, but I'm not sure when this file was last updated. (Yes, I am using a non-admin account in XP. It's not as easy as it should be, but it's also not as hard as you might think.)

夏の忆 2024-10-03 12:35:04

以下代码将帮助您检索在特定端口上运行的进程的 PID。在本例中为 5556。

import subprocess
import re

port = 5556
data = subprocess.check_output(['lsof', '-i:{}'.format(port)]).decode().split('\n')[1]
pid = re.match('^([a-zA-Z0-9]+)(\s+)([0-9]+)\s', data).groups()[2]
print(pid)

The following code will help you retrieve the PID of a process running on a particular port. In this case it is 5556.

import subprocess
import re

port = 5556
data = subprocess.check_output(['lsof', '-i:{}'.format(port)]).decode().split('\n')[1]
pid = re.match('^([a-zA-Z0-9]+)(\s+)([0-9]+)\s', data).groups()[2]
print(pid)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文