Bhavani Kannan
Bhavani Kannan

Reputation: 1279

Checking for Not Listening Ports from Batch File

I am writing a batch file to automate certain redundant tasks. In the process, I need to find a port that is not listening so I can use it to install some services.

The current test code I have is:

@echo OFF
:getPort
Set /P oPort=Enter an open port (not listening) (eg: 9335)
echo %oPort%
for /f "delims=" %%a in ('netstat -an |find /i "%oPort%"') do (
    call set concat=%%concat%%%%a
    )
echo %concat%
IF [%concat%] != [] 
echo %oPort% is already in use.
GOTO getPort

It throws error | was unexpected at this time.

What I am trying to do in the code is:

  1. Get a port number from user
  2. Run the command for example: netstat -an | find /i 9225 and store the output value in a variable
  3. If the variable is NOT empty, it means the port is listening and so I need to prompt the user for another port.

Any guidance, please.

Upvotes: 0

Views: 1924

Answers (2)

MC ND
MC ND

Reputation: 70923

netstat -an | findstr /r /c:"^  [TU][CD]P  *[^ ]*:%oPort% " >nul && goto :getPort

There is no need for the for command. Just test if the value can be found. If it can be found ask for another port.

Upvotes: 0

Monacraft
Monacraft

Reputation: 6630

Instead of using a for-loop to extract the output, I would suggest redirecting it into a file and going of that.

@echo OFF
:getPort
Set /P oPort=Enter an open port (not listening) (eg: 9335)
echo %oPort%
netstat -an |find /i "%oPort%"' > temp.tmp
set /p concat=<temp.tmp
del temp.tmp
echo %concat%
IF "%concat%" NEQ "" (
  echo %oPort% is already in use.
  GOTO getPort
)
echo %oPort% is not in use.
REM Not sure if you want to exit or continue
goto getport

Which should work.

Upvotes: 1

Related Questions