开箱即用之 windows干掉指定端口的服务

     /**
     * 关闭指定端口的windows服务
     * @param port 端口
     */
    public static void closeServiceByPort(int port)
    {
        try
        {
            String pid = findPidByPort(port);
            if (pid != null)
            {
                killProcess(pid);
            } else
            {
                throw new RuntimeException("没有找到监听在端口 " + port + " 上的服务。");
            }
        } catch (IOException e)
        {
            LOGGER.error("关闭指定端口的windows服务失败!", e);
        }
    }

    /**
     * 找到监听在指定端口的进程ID
     * @param port 端口
     * @return 进行id
     */
    public static String findPidByPort(int port)
    {
        try
        {
            // 使用ProcessBuilder构建命令
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("cmd.exe", "/c", "netstat -ano | findstr " + port);
            Process process = processBuilder.start();

            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode != 0)
            {
                throw new RuntimeException("命令执行失败,退出码: " + exitCode);
            }

            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null)
            {
                // 输出格式是 "" "TCP" "0.0.0.0:端口号" "0.0.0.0:0" "LISTENING" "进程ID"
                String[] parts = line.split("\\s+");
                if (parts.length >= 5 && "LISTENING".equalsIgnoreCase(parts[4]))
                {
                    // 确保端口号匹配
                    if (parts[2].endsWith(":" + port))
                    {
                        return parts[5]; // 返回进程ID
                    }
                }
            }
        } catch (IOException | InterruptedException e)
        {
            LOGGER.error("查找指定端口的进程ID失败:", e);
        }
        return null;
    }

    /**
     * 关闭指定进程的服务
     * @param pid 进程id
     */
    private static void killProcess(String pid) throws IOException
    {
        // 使用taskkill命令关闭进程
        Runtime.getRuntime().exec("taskkill /F /PID " + pid);
        LOGGER.info("已关闭进程ID: " + pid);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值