如何删除已分配给端口的当前进程/应用程序?

例如:localhost:8080


当前回答

下面是在WSL2中执行此操作的脚本

PIDS=$(cmd.exe /c netstat -ano | cmd.exe /c findstr :$1 | awk '{print $5}')
for pid in $PIDS
do
    cmd.exe /c taskkill /PID $pid /F
done

其他回答

Windows 10/11默认工具:

第一步:

以管理员身份打开Windows PowerShell

第二步:

查找8080端口的PID (ProcessID):

netstat -aon | findstr 8080

TCP 0.0.0.0:8080 0.0.0.0:0 listen 77777

第三步:

杀死僵尸进程:

taskkill /f /pid 77777

“77777”是你的PID

下面是在WSL2中执行此操作的脚本

PIDS=$(cmd.exe /c netstat -ano | cmd.exe /c findstr :$1 | awk '{print $5}')
for pid in $PIDS
do
    cmd.exe /c taskkill /PID $pid /F
done

用于命令行:

for /f "tokens=5" %a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %a

用于蝙蝠档案:

for /f "tokens=5" %%a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %%a

使用GitBash的一行解决方案:

 tskill `netstat -ano | grep LISTENING | findstr :8080 | sed -r 's/(\s+[^\s]+){4}(.*)/\1/'`

将8080替换为服务器正在侦听的端口。

如果您需要经常使用它,请尝试添加到~/。Bashrc函数:

function killport() {
        tskill `netstat -ano | findstr LISTENING | findstr :$1 | sed -r 's/^(\s+[^\s]+){4}(\d*)$/\1/'`
}

然后简单地运行

killport 8080

如果你使用powershell 7+,这对我有用。只需在$PROFILE文件中添加此函数。

function killport([parameter(mandatory)] [string] $uport){
    if($upid = (Get-NetTCPConnection -LocalPort $uport -ErrorAction Ignore).OwningProcess){kill $upid}
}

然后简单地使用killport 8080

或者如果你只喜欢命令,你可以试试这个:

kill $(Get-NetTCPConnection -LocalPort 8761 -ErrorAction Ignore).OwningProcess