telnet命令是TELNET協議的用戶接口,它支持兩種模式:命令模式和會話模式。雖然telnet支持許多命令,但大部分狀況下,咱們只是使用它查看目標主機是否打開了某端口(默認是23)。linux
其執行結果有兩種:ui
$ telnet 101.199.97.65 62715
Trying 101.199.97.65... telnet: connect to address 101.199.97.65: Connection refused
此時,命令已退出。code
$ telnet 101.199.97.65 62715
Trying 101.199.97.65... Connected to 101.199.97.65. Escape character is '^]'.
此時命令未退出。
根據提示Escape character is '^]'.
可知退出字符爲'^]'(CTRL+])。此時輸入其它字符不能使其退出,CTRL+C都不行。輸入CTRL+]後會自動執行,進入命令模式:接口
^]
telnet>
此時再運行quit
纔會真正退出。it
telnet> quit
Connection closed.
其中,Escape character能夠自定義,使用參數-e
:io
$ telnet -e p 101.199.97.65 62715 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.
即使如此,退出telnet仍是麻煩。那麼,更進一步,若是出如今腳本中應該如何(優雅地)退出telnet呢?sed
其實能夠這樣:協議
$ 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
$ 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.
使用這種方式能夠將標準輸出和標準錯誤重定向到文件中,經過分析文件的內容來判斷端口打開狀態。腳本