How to query netstat to find PID for specific local address in Windows 7?

元气小坏坏 提交于 2019-12-31 04:10:36

问题


I frequently start server on local address [::]:8080. To terminate server I need PID fetched from netstat -aon.

To terminate this server I do taskkill /F /PID <found pid>

I want to create windows batch file that can find PID and apply it in call taskkill /F /PID <found pid>

How can I create such batch file?

Thanks!


回答1:


On my PC there could be a UDP or TCP connection and they require slightly different code:
Test this to see if one of the taskkill commands looks right and remove echo to enable the taskkill command.

@echo off
for /f "tokens=5" %%a in ('netstat -aon ^|find " [::]:8080 " ^|find /i " TCP " ') do echo taskkill /F /PID %%a

for /f "tokens=4" %%a in ('netstat -aon ^|find " [::]:8080 " ^|find /i " UDP " ') do echo taskkill /F /PID %%a



回答2:


@echo off

    setlocal enableextensions

    set "port=8080"

    for /f "tokens=1,4,5" %%a in (
        'netstat -aon ^| findstr /r /c:"[TU][CD]P[^[]*\[::\]:%port%"'
    ) do if "%%a"=="UDP" (taskkill /F /PID %%b) else (taskkill /f /PID %%c)

    endlocal

Use findstr to retrieve only the needed record, tokenize it using the for command to get the PID column (4th for UDP, 5th for TCP) and kill the task



来源:https://stackoverflow.com/questions/24651229/how-to-query-netstat-to-find-pid-for-specific-local-address-in-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!