Windows 系统关闭特定端口的方法

Windows 系统关闭特定端口的方法

技术背景

在 Windows 系统中,有时会遇到应用程序或进程占用端口后未正常关闭的情况。例如,当网络中断导致 SSH 连接丢失,但端口仍然保持打开状态。这种情况下,就需要手动关闭这些占用的端口,以释放资源并避免后续使用该端口时出现冲突。

实现步骤

方法一:使用 netstattaskkill 命令

  1. 查找占用端口的进程 PID
    打开命令提示符(CMD),可能需要以管理员身份运行。运行以下命令,将 <PORT> 替换为你要关闭的端口号:
1
netstat -ano | findstr :<PORT>

命令执行后,会显示占用该端口的进程的相关信息,其中包括 PID(进程标识符)。
2. 终止该进程
找到 PID 后,运行以下命令来终止该进程:

1
taskkill /PID <PID> /F

其中,<PID> 是上一步查找到的进程 ID,/F 表示强制终止进程。
3. 验证操作结果
重新运行第一步的命令,如果没有搜索结果,说明端口已成功关闭。

方法二:使用 npx kill - port 命令

此方法需要安装 Node.js 和 npm(Node.js 包管理器)。在命令提示符或 PowerShell 中运行以下命令:

1
npx kill - port <PORT>

<PORT> 替换为你要关闭的端口号。该命令会自动查找并终止占用该端口的进程。

方法三:使用 PowerShell 命令

  1. 查找占用端口的进程 PID
    以管理员身份打开 Windows PowerShell,运行以下命令,将 3000 替换为你要关闭的端口号:
1
netstat -aon | findstr 3000

命令会显示占用该端口的进程的 PID。
2. 终止该进程
运行以下命令来终止进程:

1
taskkill /f /pid <PID>

<PID> 替换为上一步查找到的进程 ID。

方法四:自动化脚本

可以创建一个 .bat 文件来自动化上述过程。以下是一个示例:

1
2
3
4
5
6
7
@echo off
set /P port="Enter port : "
echo showing process running with port %port%
netstat -ano|findstr "PID :%port%"
set /P pid="Enter PID to kill : "
taskkill /pid %pid% /f
set /P exit="Press any key to exit..."

运行该 .bat 文件,按照提示输入端口号和 PID,即可完成端口关闭操作。

核心代码

Python 代码示例

1
2
3
4
5
6
7
8
from psutil import process_iter
from signal import SIGTERM

for proc in process_iter():
for conns in proc.connections(kind='inet'):
if conns.laddr.port == 8080:
proc.send_signal(SIGTERM)
continue

这段 Python 代码使用 psutil 库来查找占用指定端口(如 8080)的进程,并发送终止信号 SIGTERM 来终止该进程。

Node.js 代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const { exec } = require('child_process');
const fs = require('fs');

const port = process.argv.length > 2 ? process.argv[2] : '';
if (!port || isNaN(port)) console.log('port is required as an argument and has to be a number');
else {
exec(`netstat -ano | findstr :${port}`, (err, stdout, stderr) => {
if (!stdout) console.log(`nobody listens on port ${port}`);
else {
const res = stdout.split('\n').map(s => s.trim());
const pid = res.map(s => s.split(' ').pop()).filter(s => s).pop();
console.log(`Listener of ${port} is found, its pid is ${pid}, killing it...`);
exec(`taskkill /PID ${pid} /F`, (err, stdout, stderr) => {
if (!stdout) console.log(`we tried to kill it, but not sure about the result, please run me again`);
else console.log(stdout);
})
}
});
}

这段 Node.js 代码通过 child_process 模块执行系统命令,查找占用指定端口的进程的 PID,并使用 taskkill 命令终止该进程。

最佳实践

  • 以管理员身份运行命令:某些情况下,需要以管理员身份运行命令提示符或 PowerShell 才能成功终止进程。
  • 使用自动化脚本:如果经常需要关闭特定端口,可以创建自动化脚本,提高效率。
  • 检查进程是否可终止:在终止进程之前,确保该进程可以被安全终止,避免影响系统正常运行。

常见问题

  • taskkill 命令提示权限不足:以管理员身份运行命令提示符或 PowerShell 来解决。
  • npx kill - port 命令无效:确保已安装 Node.js 和 npm,并且网络连接正常。
  • PID 为 0 无法终止:PID 为 0 通常表示系统进程,不能被终止。需要检查是否查找错误或使用其他方法解决端口占用问题。

Windows 系统关闭特定端口的方法
https://119291.xyz/posts/2025-04-23.windows-specific-port-closing-methods/
作者
ww
发布于
2025年4月23日
许可协议