Windows batch file - list listening ports with owning process
How to list each Windows process that is listening on a network port?
Build up the command as follows:
- netstat is a most useful Windows command to list network connections and open ports. Generally I use
-aonas arguments to list everything and associated process by pid in its output.
- use find to filter on the LISTENING status we're interested in
- use a for loop to execute that netstat / find output and iterate and process the output
- for each line (which corresponds to an open listening port) use
tasklistwith a filter argument to to turn the pid into some process details for the same.
SO the complete one line cmd as follows
for /f "tokens=2,5" %t in ( 'netstat -aon ^| find "LISTEN"' ) do @for /f %p in ( 'tasklist /fi "pid eq %u" /fo csv /nh' ) do @echo %t %p
OR stick that into a batch file, basically the same just allowing for the now required double %% and split the line for readability
@echo off for /f "tokens=2,5" %%t in ( 'netstat -aon ^| find "LISTEN"' ) do ( for /f %%p in ( 'tasklist /fi "pid eq %%u" /fo csv /nh' ) do echo %%t %%p )