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 comman
Here is the clean way to do it
echo -n | telnet `hostname` 2878
For more info on this behavior see this link
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] $
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
╭─ ~
╰» 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.
You may need other linux package like expect
to achieve what you want.