3

I am using Windows 7 x64. Using a bat script, I need to check whether I am able to connect to some specific ports on a server using telnet. If successfully connected, the server displays a menu, or else a message like this : Connecting To xxxxx...Could not open connection to the host, on port xxxxx: Connect failed.

For my purpose, the server has several ports to be tested and I don't want to complicate things by logging in or navigating menus. I just want a simple output indicating whether the connection was successful or not. Checking for exit status didn't work. I don't want to use Visual Basic. Any idea how check the connection status using a bat script? Currently I check visually and I use the below script to open connections

@ECHO OFF
setlocal EnableDelayedExpansion

echo.
SET /P host_name="Please enter the hostname: "
echo Please enter the port numbers followed by the Enter key: 
echo.
set num=0

:Loop
set /a num=num+1
SET /P mwa_port%num%=""
if "!mwa_port%num%!"=="" (goto Start)
goto Loop

:Start
set /a num=num-1
for /L %%i in (1,1,%num%) do (
 echo Trying to log into port !mwa_port%%i! of %host_name%
 start /min "" "C:\Windows\System32\telnet.exe" %host_name% !mwa_port%%i!
 REM echo Exit Code is %errorlevel%
)

:End
endlocal
echo.
SET /P leave="Press any key to exit.."

Here is a sample output of the script :

Please enter the hostname : abcdefg.hijkl.mnop
Please enter the port numbers followed by the Enter key:

10001
10002
10003
10004
10005

Trying to log into port 10001 of abcdefg.hijkl.mnop
Trying to log into port 10002 of abcdefg.hijkl.mnop
Trying to log into port 10003 of abcdefg.hijkl.mnop
Trying to log into port 10004 of abcdefg.hijkl.mnop
Trying to log into port 10005 of abcdefg.hijkl.mnop

Press any key to exit..

It then opens 5 telnet windows in minimized state, each one with a menu on successful login

Shivanand
  • 144
  • 1
  • 1
  • 13
  • 1
    Windows telnet.exe isn't scriptable. Additionally, you can't pipe the output through find.exe and when a connection succeeds then the window will hang. There is a scriptable telnet tool `Telnet Scripting Tool v.1.0` which may help you. – foxidrive Dec 15 '13 at 00:47

3 Answers3

4

It's a shame you can't use netcat - are all open source options like it off-limits in your environment?

Even without open source tools, you can still accomplish this task with PowerShell.

Here's a sample PS script that will try to connect to port 23 on $remoteHost and exit 0 on success, and 1 on failure. (If you need to do more work once connected, a few examples of more complex PowerShell telnet clients are available on the web, such as this one.)

Place the code in the file "foo.ps1", then run in cmd.exe (or from a .bat file) with "powershell -File foo.ps1". When it exits, the exit code will be stored in %errorlevel%.

Note you may need to modify your PowerShell script execution policy (or use the "-ExecutionPolicy Bypass" cmdline option) to allow execution of the script - for more info see this documentation from MSFT.

param(
    [string] $remoteHost = "arbitrary-remote-hostname",
    [int] $port = 23
     )

# Open the socket, and connect to the computer on the specified port
write-host "Connecting to $remoteHost on port $port"
try {
  $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
} catch [Exception] {
  write-host $_.Exception.GetType().FullName
  write-host $_.Exception.Message
  exit 1
}

write-host "Connected.`n"
exit 0
Community
  • 1
  • 1
Bill Agee
  • 3,606
  • 20
  • 17
  • `D:\*********>powershell -File test.ps1 File D:\**********\test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details. + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RuntimeException` – Shivanand Dec 16 '13 at 07:05
  • 1
    Yes, that's why I mentioned you need to either use "-ExecutionPolicy Bypass" or follow the directions on the MS documentation link I posted. :) See the paragraph just above the code snippet I posted. Or, you can google the error string for more accounts of how to get around the policy. – Bill Agee Dec 16 '13 at 14:48
  • 1
    When opening the powershell from the cmd console, just start it with "powershell -ExecutionPolicy ByPass" - then execute the powershell commands. – razvanone Sep 06 '16 at 10:08
  • Better to close the connected socket if it's not intended to be used `$socket.close();` after successful connection. – Davut Gürbüz Mar 20 '22 at 15:34
2

you can use netcat, session log:

    C:\Users\User>nc -v -t stackoverflow.com 23
    stackoverflow.com [198.252.206.16] 23 (telnet): TIMEDOUT

    C:\Users\User>echo %errorlevel%
    1

    C:\Users\User>nc -v -t stackoverflow.com 25
    stackoverflow.com [198.252.206.16] 25 (smtp) open
    220 SMTP Relay SMTP
    421 SMTP Relay SMTP session timeout. Closing connection

    C:\Users\User>echo %errorlevel%
    0
Endoro
  • 37,015
  • 8
  • 50
  • 63
  • Due to security policies at workplace, I can only use tools from trusted sources. I won't be able to use netcat. Is there any other way? – Shivanand Dec 15 '13 at 05:07
  • just take `snetcat` binaries from a 'trusted source' : [sourceforge](http://snetcat.sourceforge.net/), you get the same `errorlevel` results. – Endoro Dec 15 '13 at 17:20
  • Security policies that allow trusted sources only will block Sourceforge in general. – karatedog Jan 28 '22 at 08:19
0

What do you mean by Checking for exit status didn't work.?

If you un-REM your Exit-code print line, the response will be that ERRORLEVEL will be the value of errorlevel when the FOR loop was parsed - prior to execution.

To display the value as it changes for each invocation of telnet you'd need

 ...
 "C:\Windows\System32\telnet.exe" %host_name% !mwa_port%%i!
 echo Exit Code is !errorlevel!

where !errorlevel! is the run-time value of errorlevel.

In all probability, you'd want to suppress the telnet output, so >nul and/or 2>nul may be usefully attached to quieten it down. Possibly youd need to provide telnet with a response - not my area...

Now - if errorlevel doesn't return a usable value, is there any telnet response that can be observed to distinguish between the states in which you are interested?

Magoo
  • 77,302
  • 8
  • 62
  • 84