Auto exit Telnet command back to prompt without human intervention ^] quit close exit code 1

混江龙づ霸主 提交于 2019-12-06 03:46:14

A slight improvement to the answer provided by Matthew above which allows you to use it inside shell scripts:

$ echo -e '\x1dclose\x0d' | telnet google.com 80
Connected to google.com.
Escape character is '^]'.

telnet> close
Connection closed.
$ echo $?
0

You may need other linux package like expect to achieve what you want.

Without using Expect, I guess using the HERE document (<

[vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 2878 <<GIGA
echo ^]
echo close
GIGA
); echo $telnet_result | grep "Escape character is '^]'"; echo $?
Connection closed by foreign host.
 Escape character is '^]'.
0
[vagrant@myvagrant /tmp] $ 

and for a bad/invalid/non-open port, the same gives 1 (as expected).

[vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 287811111 <<GIGA
echo ^]
echo close
GIGA
); echo $telnet_result | grep "Escape character is '^]'"; echo $?
telnet: connect to address 127.0.0.1: Connection refused
1
[vagrant@myvagrant /tmp] $ 
╭─ ~
╰» echo "^]close^M" | telnet localhost 22; echo $?
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

telnet> close
Connection closed.
0

To enter the ^] and ^M characters, press ctrl+v ctrt+] and ctrl+v ctrl+m respectively.

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