Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm running telnet command on a host for a given port (which is open), it returns 0 (success).

For trying telnet manually, I type the following command, then I press control+bracket i.e. ^], then press Enter key, then I get to telnet> prompt, where if I type close or quit, it comes back to the $ prompt and seeing exit status of last command shows 0 for (success) as port 2878 is open (as per the telnet command's output).

[vagrant@myvagrant /tmp] $ telnet `hostname` 2878
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
^]

telnet> close
Connection closed.
[vagrant@myvagrant /tmp] $ echo $?
0

Now, I wanted to run the same operation without any human intervention i.e. I don't want to manually give ^] and press Enter key to come to the telnet> prompt, then enter close (or quit) telnet command to finally come back to the $ prompt.

For this, I tried using echo -e command's option and giving ^], \n (for new line character i.e. Enter key) and close command (for telnet> prompt so that I come back to $ prompt). Doing this, kind of worked as expected but for the exit status of last command echo $?, I'm getting 1 (instead of 0). Why?

[vagrant@myvagrant /tmp] $ echo -e "^]\nclose" | telnet `hostname` 2878
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
Connection closed by foreign host.
[vagrant@myvagrant /tmp] $ 
[vagrant@myvagrant /tmp] $ echo $?
1
[vagrant@myvagrant /tmp] $ 

or tried the here-doc method as well, but not sure why it's returning 1 (as exit code) for a valid port which is open.

[vagrant@myvagrant /tmp] $ telnet `hostname` 2878 <<GIGA
> echo ^]
> echo close
> GIGA
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
Connection closed by foreign host.
[vagrant@myvagrant ~/aks/always-latest-ws-sunny] $ echo $?
1
[vagrant@myvagrant ~/aks/always-latest-ws-sunny] $

How can I automatically exit from telnet if the port is open and get 0 as exit code? If there's a way to capture the output of the previous command, may be I can grep the 'Connection closed by foreign host.' string to mark it successful (0).

like image 871
AKS Avatar asked Jan 05 '17 01:01

AKS


1 Answers

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
like image 67
Maxim Akhmedov Avatar answered Nov 01 '22 19:11

Maxim Akhmedov