Home >System Tutorial >LINUX >Port connectivity test: how to use telnet gracefully

Port connectivity test: how to use telnet gracefully

王林
王林forward
2024-01-01 21:59:511135browse

The telnet command is the user interface of the TELNET protocol. It supports two modes: command mode and session mode. Although telnet supports many commands, in most cases, we just use it to check whether the target host has opened a certain port (default is 23).
Port connectivity test: how to use telnet gracefully

There are two execution results: Port not open
$ telnet 101.199.97.65 62715
Trying 101.199.97.65...
telnet: connect to address 101.199.97.65: Connection refused

At this point, the command has exited.

Port is open
$ telnet 101.199.97.65 62715
Trying 101.199.97.65...
Connected to 101.199.97.65.
Escape character is '^]'.

The command has not exited at this time.
According to the prompt Escape character is '^]'. It can be seen that the exit character is '^]' (CTRL]). Entering other characters at this time will not make it exit, even CTRL C will not work. After entering CTRL ], it will be automatically executed and enter the command mode:

^]
telnet>

Running quit at this time will actually exit.

telnet> quit
Connection closed.

Among them, the Escape character can be customized, using the parameter -e:

$ telnet -e p 101.199.97.65 62715   #使用p字符
Telnet escape character is 'p'.
Trying 101.199.97.65...
Connected to 101.199.97.65.
Escape character is 'p'.
p
telnet> quit
Connection closed.

Even so, exiting telnet is still troublesome. So, going one step further, how should I (gracefully) exit telnet if it appears in a script?

plan

In fact, it can be like this:

Exit immediately after outputting the results
$ echo "" | telnet 101.199.97.65 62715

Trying 101.199.97.65...
Connected to 101.199.97.65.
Escape character is '^]'.
Connection closed by foreign host.  #已成功连通端口并自动退出
$ echo "" | telnet 101.199.97.65 62715
Trying 101.199.97.65...
telnet: connect to address 101.199.97.65: Connection refused #端口未开放
Delayed exit after outputting results

sleep 2 causes telnet to output the results and stay for 2 seconds before exiting the command mode.

$ sleep 2 | telnet 101.199.97.65 62715

Trying 101.199.97.65...
Connected to 101.199.97.65.
Escape character is '^]'.
Connection closed by foreign host.

Using this method, the standard output and standard error can be redirected to a file, and the port open status can be determined by analyzing the contents of the file.

The above is the detailed content of Port connectivity test: how to use telnet gracefully. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:linuxprobe.com. If there is any infringement, please contact admin@php.cn delete