Automate telnet port testing on Windows 7 using batch script

守給你的承諾、 提交于 2019-12-04 12:41:39
Bill Agee

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

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

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?

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