您可以使用该psutil
模块获取进程和网络信息
import psutil
import pprint
for process in psutil.process_iter():
### find which ports is the listening (if any)
listening_ports = [conn for conn in process.get_connections() if conn.status == psutil.CONN_LISTEN]
if len(listening_ports) > 0:
print("PID: {}, Process Name: {}".format(process.pid, process.name))
print("Connections:")
pprint.pprint(listening_ports)
### You could check the desired process and terminate/kill it
# process.terminate()
Windows 上的示例输出,该模块也支持 Linux(列出所有监听进程):
PID: 664, Process Name: lsass.exe
Connections:
[connection(fd=-1, family=2, type=1, laddr=('0.0.0.0', 49155), raddr=(), status='LISTEN'),
connection(fd=-1, family=23, type=1, laddr=('::', 49155), raddr=(), status='LISTEN')]
PID: 904, Process Name: svchost.exe
Connections:
[connection(fd=-1, family=2, type=1, laddr=('0.0.0.0', 135), raddr=(), status='LISTEN'),
connection(fd=-1, family=23, type=1, laddr=('::', 135), raddr=(), status='LISTEN')]
PID: 1712, Process Name: SpiderOak.exe
Connections:
[connection(fd=-1, family=2, type=1, laddr=('127.0.0.1', 49201), raddr=(), status='LISTEN'),
connection(fd=-1, family=2, type=1, laddr=('0.0.0.0', 49258), raddr=(), status='LISTEN')]
使用所有这些信息,您可以找到您的进程,甚至可以使用psutil.Process
方法terminate()
(发送SIGTERM
信号)或kill()
(发送SIGKILL
信号,就像kill -9
)杀死它