在python中,有一种跨平台的方法来确定正在侦听给定端口的进程? [英] In python is there a cross-platform way of determining what process is listening to a given port?
问题描述
在linux中,我可以使用 lsof -i
,如以下功能所示:
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?
作为相关参考,一旦我知道了进程ID, psutil 库就非常有用.很好,让我以跨平台的方式为它确定各种有用的过程信息.我现在暂时无法跨平台工作(找到pid).
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.
如果不熟悉 lsof -i
开关,则输出如下所示(在启动python进程后,该进程打开了一个侦听端口1234的TCP套接字):
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)
推荐答案
不,这不是python内置的.
No, this is not built into python.
这篇关于在python中,有一种跨平台的方法来确定正在侦听给定端口的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!