Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,是否有可能终止侦听特定端口(例如8080)的进程?_Python_Python 2.7 - Fatal编程技术网

在python中,是否有可能终止侦听特定端口(例如8080)的进程?

在python中,是否有可能终止侦听特定端口(例如8080)的进程?,python,python-2.7,Python,Python 2.7,在python中,是否有可能终止在特定端口(例如8080)上侦听的进程 我可以执行netstat-ltnp | grep8080和kill-9或从python执行shell命令,但我想知道是否已经有一些模块包含API,可以按端口或名称终止进程?您可以使用。一些未经测试的代码应该为您指明正确的方向: from psutil import process_iter from signal import SIGTERM # or SIGKILL for proc in process_iter():

在python中,是否有可能终止在特定端口(例如8080)上侦听的进程

我可以执行
netstat-ltnp | grep8080
kill-9
或从python执行shell命令,但我想知道是否已经有一些模块包含API,可以按端口或名称终止进程?

您可以使用。一些未经测试的代码应该为您指明正确的方向:

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

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


正如Toote所说,
psutil
为您提供了
netstat
功能。您还可以使用
os.kill
发送kill信号(或按Toote的方式执行)。

在端口上终止进程的最简单方法是使用python库:freeport()。一旦安装,只需:

# install freeport
pip install freeport

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

此处提供了实现详细信息:

您可以使用子流程来完成此操作,然后将其终止

import os
import signal
from subprocess import Popen, PIPE

port = 1234
process = Popen(["lsof", "-i", ":{0}".format(port)], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
for process in str(stdout.decode("utf-8")).split("\n")[1:]:       
    data = [x for x in process.split(" ") if x != '']
    if (len(data) <= 1):
        continue

    os.kill(int(data[1]), signal.SIGKILL)
导入操作系统
输入信号
从子流程导入Popen、PIPE
端口=1234
process=Popen([“lsof”、“-i”、“:{0}.format(port)],stdout=PIPE,stderr=PIPE)
stdout,stderr=process.communicate()
对于str(stdout.decode(“utf-8”)).split(“\n”)[1:]中的进程:
数据=[x代表进程中的x。如果x!='',则拆分(“”)

如果(len(data)我试过这个方法,它对我有效

import os
import signal
import subprocess

command = "netstat -ano | findstr 8080"
c = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = c.communicate()
pid = int(stdout.decode().strip().split(' ')[-1])
os.kill(pid, signal.SIGTERM)

我使用的上述解决方案的变体:

import os
import signal
import subprocess

command = 'lsof -t -i:' + str(pid)
c = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = c.communicate()
if stdout == b'':
    return
pid = int(stdout.decode())
os.kill(pid, signal.SIGTERM)

我有“拒绝访问”运行此代码。如何“sudo”
proc.get\u connections(kind='inet')
?为什么不首先使用
sudo
运行整个程序?因为当它在远程服务器上运行时,我不会直接控制它。而且因为整个程序都是在django中运行测试,而在使用sudoa运行时会失败。据我所知,这与使用sudo运行脚本不同首先,如果你不能像那样杀死它,这可能意味着进程(你试图杀死的进程)使用sudo或从其他用户运行,因此需要使用sudo或从同一个用户删除它。冗余
继续
@KardiTeknomo是否安装了freeport库?我添加了安装freeport的命令是的,我安装了freeport,但它不起作用。使用netstat-ano | findstr:8080和taskkill/PID foundPID/F的性能要好得多
freeport
,因此可能无法在Windows上运行。上面回答的
psutil
是一种跨平台解决方案。