/**
* 关闭指定端口的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);
}
开箱即用之 windows干掉指定端口的服务
最新推荐文章于 2024-06-15 23:12:29 发布