是否可以在 python 中杀死正在侦听特定端口(例如 8080)的进程? [英] Is it possible in python to kill process that is listening on specific port, for example 8080?

查看:62
本文介绍了是否可以在 python 中杀死正在侦听特定端口(例如 8080)的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 python 中杀死正在侦听特定端口(例如 8080)的进程?

Is it possible in python to kill a process that is listening on a specific port, say for example 8080?

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

I can do netstat -ltnp | grep 8080 and kill -9 <pid> OR execute a shell command from python but I wonder if there is already some module that contains API to kill process by port or name?

推荐答案

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

You could use the psutil python module. Some untested code that should point you in the right direction:

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

这篇关于是否可以在 python 中杀死正在侦听特定端口(例如 8080)的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆