In python is there a cross-platform way of determining what process is listening to a given port?

落爺英雄遲暮 提交于 2021-01-27 17:42:57

问题


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)

回答1:


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)



回答2:


No, this is not built into python.




回答3:


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.)




回答4:


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)


来源:https://stackoverflow.com/questions/3874481/in-python-is-there-a-cross-platform-way-of-determining-what-process-is-listening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!