快速终止端口所在进程

2024年4月27日00:36:09 发表评论 175 views

最近特别烦,每次重启后部分程序霸占着1080和1081端口,导致v2ray和ss根本无法启动,然后还得手动去终止一遍,现在好了,写一个程序自动去终止这些进程。

import subprocess

def kill_process_on_port(port):
    command = f'netstat -ano | findstr :{port}'
    result = subprocess.check_output(command, shell=True).decode()
    pids = []
    for i in result.split('\n'):
        print(i)
        _ = i[-8:].replace(' ', '')
        _ = _.replace('\r', '')
        pids.append(_)

    print(pids)
    for pid in pids:
        print(pid)
        subprocess.run(f'taskkill /F /PID {pid}', shell=True)

if __name__ == '__main__':
    try:
        kill_process_on_port(1080)
    except Exception as e:
        pass
    try:
        kill_process_on_port(1081)
    except Exception as e:
        pass

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: