python通过端口号杀死进程

方式一:

import psutil


def kill_by_port(port):
    for conn in psutil.net_connections():
        if conn.laddr.port == port and conn.status == 'LISTEN':
            p = psutil.Process(conn.pid)
            p.terminate()

方式二:

仅适用于windows

import subprocess
import re


def kill_by_port(port):
    c = subprocess.getoutput(f'netstat -ano | findstr {port} |findstr LISTENING ')
    pids = re.findall('(\d+)\n', c)
    for pid in set(pids):
        if int(pid) > 0:
            subprocess.run(f"taskkill /pid {pid} -f")

你可能感兴趣的:(python,开发语言,python)