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 (the default is 23) .
There are two types of 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 '^]'.
At this point the command did not exit.
According to the prompt Escape character is '^]'. It can be seen that the escape character is '^]' (CTRL+]). At this time, entering other characters cannot make it exit, even CTRL+C will not work. After entering CTRL+], it will be executed automatically and enter the command mode:
^] telnet>
At this time, run quit again to actually exit.
telnet> quit Connection closed.
Among them, the Escape character can be customized, using the parameter -e:
$ telnet -ep 101.199.97.65 62715 #Use the p character 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, logging out of telnet is 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 result
$ 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. #The port has been successfully connected and exited automatically
$ echo "" | telnet 101.199.97.65 62715 Trying 101.199.97.65... telnet: connect to address 101.199.97.65: Connection refused #The port is not open
Delayed exit after outputting the result
sleep 2 makes telnet output the result, stay for 2 seconds and then exit 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.
In this way, the standard output and standard error can be redirected to a file, and the port opening status can be judged by analyzing the content of the file.