是否有可能在python中杀死正在侦听特定端口的进程,例如8080?

问题描述 投票:3回答:3

是否有可能在python中杀死正在侦听特定端口的进程,例如8080?

我可以做netstat -ltnp | grep 8080kill -9 <pid>或者从python执行shell命令但是我想知道是否已经有一些模块包含按端口或名称杀死进程的API?

python python-2.7
3个回答
9
投票

你可以使用psutil python module。一些未经测试的代码应该指向正确的方向:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL

2
投票

杀死端口进程的最简单方法是使用python库:freeport(https://pypi.python.org/pypi/freeport/0.1.9)。安装完成后,只需:

# install freeport
pip install freeport

# Once freeport is installed, use it as follows
$ freeport 3000
Port 3000 is free. Process 16130 killed successfully

有关实施细节,请访问:https://github.com/yashbathia/freeport/blob/master/scripts/freeport


1
投票

首先,进程不在端口上运行 - 进程可以绑定到特定端口。特定端口/ IP组合只能在给定时间点由单个进程绑定。

正如Toote所说,psutil为您提供netstat功能。您也可以使用os.kill发送终止信号(或者使用Toote的方式)。

© www.soinside.com 2019 - 2024. All rights reserved.