python 脚本 解决 windows 端口占用问题

使用Python执行脚本即可

import os

# 无论合适输入q 即退出  quit
global_command_exit = 'q'


def find_and_kill(port):
    """
    通过端口号查找指定的进程,并提供展示进程信息和 杀掉进程的功能.
    :param port:  待操作的端口号
    """
    # 无法获取返回值
    # result = os.system('netstat -ano | findstr "10000" ')
    result = os.popen(f'netstat -ano | findstr "{port}" ')
    find_result = result.read()
    if len(find_result.strip()) is 0:
        print("当前端口号未被占用")
        return None
    print(f'占用当前端口的程序如下:\n{find_result}')
    # 将所有的进程信息分割开.
    processors = find_result.split("\n")
    # 过滤掉空白行
    real_processors = []
    for processor in processors:
        if processor.strip() is "":
            continue
        # 将有效的进程信息放入最终的结果集中.
        real_processors.append(processor)

    # 提示要 kill 哪个 pid
    pid_str = input('请输入要查看的进程PID:')

    while pid_str.strip() is '':
        pid_str = input('pid 不能是空,请重新输入:')

    if pid_str.strip() is global_command_exit:
        print(f'exit process with command q')
        return None
    # tasklist | findstr 20648
    process_info = os.popen(f'qprocess {pid_str}')
    print(f'进程信息:********************************************\n{process_info.read()}')

    pid_str = input('请输入要杀掉的进程PID:')
    while pid_str.strip() is '':
        pid_str = input('pid 不能是空,请重新输入:')

    if pid_str.strip() is global_command_exit:
        print(f'exit process with command q')
        return None
    # 杀进程.
    # taskkill -t -f /pid
    process_info = os.popen(f'taskkill -t -f /pid  {pid_str}')
    print(f'进程信息:********************************************\n{process_info.read()}')
    print(f'任务结束')


if __name__ == '__main__':
    target_pid = input('请输入端口号:')
    while target_pid.strip() is '':
        target_pid = input('端口号 不能是空,请重新输入:')

    if target_pid.strip() is global_command_exit:
        print(f'exit process with command q')
    else:
        find_and_kill(target_pid)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值