天天看點

windows 關閉端口被占用腳本

cmd 關閉程序java

taskkill /F /IM java.exe

taskkill /f /im java.exe

如何用dat批處理檔案關閉某端口對應程式-Windows自動化指令

如何用dat批處理檔案關閉某端口對應程式?

網上找到的大部分都是手動操作,第一步先查出端口,第二步在根據上一步查到的端口手動去關閉程序。但我的需求不是這樣的,我需要全自動處理。用于 dubbo 服務程序在 Windows 環境下的關閉。如果 Linux 環境,則不需那麼辛苦了。

找了大半天,終于在百度知道上得到參考案例(或許是我使用的關鍵詞不對),并成功試驗,感謝相關貢獻者。

答案一:

for /f "tokens=1-5 delims= " %%a in ('"netstat -ano|findstr "^:指定端口号""') do taskkill /pid %%e      

答案二:

​ ​

​ ​

​@echo off​

​ ​

​ ​

​set port=1234​

​ ​

​ ​

​for /f "tokens=1-5" %%i in ('netstat -ano^|findstr ":%port%"') do taskkill /pid %%m​

​ ​

我自己試驗成功的腳本如下:不加/f就關不掉

@echo off

REM 聲明采用UTF-8編碼

chcp 65001

set port=9999

for /f "tokens=1-5" %%i in ('netstat -ano^|findstr ":%port%"') do (

    echo kill the process %%m who use the port %port%

    echo 正在關閉,請等待 %%m

    taskkill /f /pid %%m

)

pause

循環讀取一批端口,并查詢對應PID是否存在,若存在則關閉,腳本如下:

​ ​

​ ​

​@echo off​

​ ​

​ ​

​for /l %%n in (20801,1,20812) do (​

​ ​

​ ​

​ @echo find the process which use port [%%n]​

​ ​

​ ​

​ for /f "tokens=1-5" %%i in ('netstat -ano^|findstr ":%%n"') do (​

​ ​

​ ​

​ tasklist /FI "PID eq %%m"|find /i "PID" && (​

​ ​

​ ​

​ echo PID:%%m 運作中,kill the process [%%m] who use the port [%%n]​

​ ​

​ ​

​ taskkill /F /pid %%m​

​ ​

​ ​

​ ) || echo PID:%%m 未運作 ​

​ ​

​ ​

​ )​

​ ​

​ ​

​)​

​ ​