SoFunction
Updated on 2025-04-08

The open port of this machine and the batch processing of processes using this port


@echo off
color 1f
Title XP port - process query
setlocal enabledelayedexpansion
echo ╔- -╗
echo the open port of the machine and the process using this port
echo ╚- -╝
echo ------------------------------------
echo port number process name
ECHO TCP protocol:
::Use the netstat command to find out the ports that use the TCP protocol to communicate and divide the result;
:: Pass the second parameter (IP plus port) to %%i, and pass the fifth parameter (PID number) to %%j;
for /F "usebackq skip=4 tokens=2,5" %%i in (`"netstat -ano -p TCP"`) do (
call :Assoc %%i TCP %%j
echo !TCP_Port! !TCP_Proc_Name!
)

ECHO UDP protocol:
for /F "usebackq skip=4 tokens=2,4" %%i in (`"netstat -ano -p UDP"`) do (
call :Assoc %%i UDP %%j
echo !UDP_Port! !UDP_Proc_Name!
)
echo Press any key to exit
pause>nul

:Assoc
::Split %1 (first parameter) and pass the second parameter to %%e. In this program, %1 is the above %%i (form: IP: port number)
for /F "tokens=2 delims=:" %%e in ("%1") do (
set %2_Port=%%e
)
:: Query the process with PID equal to %3 (the third parameter) and pass the result to the variable?_Proc_Name,? represents UDP or TCP;
for /F "skip=2 usebackq delims=, tokens=1" %%a in (`"Tasklist /FI "PID eq %3" /FO CSV"`) do (
::%%~a means removing the quotes outside %%a, because the result of the above command is enclosed in brackets.
set %2_Proc_Name=%%~a
)