Windows under BAT batch script use Telnet to bulk detect remote ports Small kee _dos/bat

Source: Internet
Author: User
Tags goto mongodb postgresql redis

After years of not writing batch processing, the first case of the new company is to write a bat script, batch update collection agent configuration file, which involves remote IP port detection.
This thought would be as simple as Linux to judge:

code as follows:

echo q|telnet-e ' q ' $ip $port && echo "$ip:p ort Tong" | | echo "$ip:p ort.

It turns out that Windows Telnet below has no return value for the results:

First, with the help of tools

So I give priority to the lazy rule, find other alternative tools. Sure enough, at the Windows old Maiden found:
It can be used, but the speed of detection is not flattering, pass and impassability are very slow! Given that there is no better solution on hand, try it first and post my PortQry related demo:

:: Using the Microsoft Official tool "PortQry" to detect code:
@echo off & setlocal enabledelayedexpansion

rem to detect IP and port
set server_ip= ',, '
set serverport= ' 9922 '

REM modular call

::* * * * * OTHER code slightly * * * *

: Check
rem※ probe Port module--portqry scheme ※
for/f "tokens=1,* delims=,"%%i in ("!server_ip!") do (
 echo is detecting%%i !serverport! Port ...
 REM This is the key detection code:
 "!tools_dir!\portqry.exe"-n%%i-p tcp-e!serverport! | find "Listenin" >nul && (
  EC Ho "Success": Can connect to%%i:!serverport!
  || (
  echo "failed": Unable to connect%%i:!serverport!
 set server_ip=%%j
 goto check
::* Hu Jintao other code slightly ********

Ps:check is a call called module, some of the variables are not introduced.
So excitedly packaged into an EXE, to IDC (SERVER2003 system) implementation, the results of the first tragedy! The remote Desktop is disconnected directly:

And then can not even go to the computer room to see the next, the results tell me the system has not!!?? Too good to have wood? A simple text manipulation script, did you kill the system? And there are no delete commands in the script ...
To provide a bit of the boot error message, the original system boot is broken:

Personal analysis, it should be portqry this tool led to the system blue screen shutdown, which led to damage to boot!

NI, the maiden introduced the good "character"?

Alas, it seems that this tool is afraid to use, as the saying goes, what the system has a big forest!

Second, the alternative

Since the tool is not used, or continue to toss code it! The weekend before going to bed suddenly inspiration flash, think of tasklist Judge window name this "lost stunt", so just closed the book and opened, finally in GF constantly complained about this problem.
①, window judgment
The idea is simpler: Use the start command to execute the TELNET-E and exit commands in a new window, and if the port is unblocked, the newly opened window will be closed immediately, while the window will remain open for nearly half a minute, and the window name is similar to Telnet, this half a minute is enough for the script to judge if the pass is still out of date.
The above check section is then modified as follows:

:: Code detected using the telnet command
@echo off & setlocal enabledelayedexpansion

rem to detect IP and port
set server_ip= ',, '
set serverport= ' 9922 '

REM modular call

::* * * * other code slightly

: Check_port
rem※ probe Port module--telnet scheme ※
for/f "tokens=1,* delims=,"%%i in ("!server_ip!") Do (
 Echo [no.! Check_num!]: detecting%%i's!serverport! Port ... 
 REM New window to open Telnet, if the port unblocked will immediately exit, the script will be in 3 seconds to see whether the Telnet window exits, if not exit indicates that the port does not pass!
 start/min cmd.exe/k "echo q|telnet-e ' Q '%%i!serverport! & Exit "
 ping-n 3 127.1>nul
 rem Look for the cmd window named" Telnet ${ip} ", which means that this IP does not pass
 tasklist/fi" WindowTitle eq Telnet%%i "| Find "cmd.exe" >nul && (
  echo "failed": Unable to connect%%i:!serverport!
 ) | | (
  echo "Success": Can connect to%%i:!serverport!
 set server_ip=%%j
 goto check_port
:: Other code slightly ...

This solves the Windows Telnet probe remote port problem, and detection speed than Microsoft which portqry faster, and really thinking more important than technology, as long as there are ideas, any technology should not become a bottleneck!

②, process judgment "latest additions"

When using the window to judge the scheme issued by the implementation of the main room, another problem appeared! window to judge in some version of Windows is not feasible, such as the English version of the command prompt window name and the Chinese version is not the same, so this solution is also imperfect!
So, continue to scratching, came up with a second plan: by judging the number of Telnet process to determine whether the network is unblocked.

Program Ideas:

code as follows:

A. Determine whether a telnet.exe process exists before the script is executed, and if so, the number of statistics
B. Like the window judgment, use the start command to execute the telnet command at the new cmd command prompt
C. Number of telnet.exe processes that exist in the statistical system after a few seconds of delay (the presence of a telnet representation is not possible)
D. and the first statistics on the number of Telnet process calculation, we know that there are several IP is not a pass

Sample code:

:: code detected using telnet command
@echo off & setlocal enabledelayedexpansion
REM IP and port to detect
set server_ ip=',,'
set serverport='9922'
:: * * * other codes are omitted****
Rem is calculated at the beginning telnet.exe The number of processes that exist before the script is executed telnet.exe
call :telnet_ num conf
REM modular call
call :check_ port
:check_ port
set /a check_ num+=1
REM detection port module
for /f "tokens=1,* delims=," %%i in ("!server_ ip!") do (
echo [No.!check_ Num!]: detecting! Serverport! Port of%% I
::call :set_ iPSec %%i
REM uses the telnet combination command to test. If the port is unblocked, it will exit immediately. The script will check whether the telnet window exits after 3 seconds. If it does not exit, it means that the port is blocked!
start /min  cmd.exe  /k "echo q|telnet -e 'q' %%i !serverport! & exit"
set server_ ip=%%j
set total_ num=!check_ num!
goto check_ port
ping -n 3 127.1>nul
#Calculate the number of Telnet processes again, and the number of Telnet processes that existed before execution has been excluded
call :telnet_ Num
The number of echo available is:! Telnet_ num!
goto :eof
:telnet_ Num
REM detects the number of Telnet processes. The existence of Telnet before script has been excluded
set conf=0
for /f "delims=*" %%i in ('tasklist ^| findstr " telnet.exe "') do (
if "%1"=="conf" (
set /a conf+=1
) else (
set /a telnet_ num+=1
set /a telnet_ num=!telnet_ num!-!conf!
goto :eof 

It's obvious that I'm testing a few of the IP's that don't work. Unfortunately, it is not possible to know which IP is not. However, in the case of the hand is not the need for specific IP, as long as the IP to know whether the standards on the line.
Well, finally solved the problem. Clearly, more than one solution is needed at all times, rather than complacency. Otherwise, the problem will be in the burn. Again, of course, the idea is more important than technology.

Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.