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

例如:localhost:8080


当前回答

在Windows PowerShell版本1或更高版本中停止端口3000上的进程:

Stop-Process (,(netstat -ano | findstr:3000).split() | foreach {$[$.length-1]}) -Force


根据@morganpdx的建议,这里有一个更像powershell的更好的版本:

Stop-Process -Id (get - netttcpconnection -LocalPort 3000)。OwningProcess force

其他回答

使用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

对于Windows用户,您可以使用CurrPorts工具轻松地杀死正在使用的端口:

我为此写了一个很小的node js脚本。就像这样运行它: node killPort.js 8080或任何你需要杀死的端口。保存如下文件到killPort.js文件中:

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);
            })
        }
    });
}

用于命令行:

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

我在Windows上运行zookeeper,无法使用zookeeper-stop.sh停止在2181端口运行的zookeeper,所以尝试了这个双斜线“//”方法来kill任务。它工作

     1. netstat -ano | findstr :2181
       TCP    0.0.0.0:2181           0.0.0.0:0              LISTENING       8876
       TCP    [::]:2181              [::]:0                 LISTENING       8876

     2.taskkill //PID 8876 //F
       SUCCESS: The process with PID 8876 has been terminated.