Wednesday, October 27, 2021

[SOLVED] How to capture the output of telnet command in a variable in Shell script

Issue

I need to run the telnet command on a remote server using shell script and have to capture the output. When i execute the below, it is not getting completed but instead getting hung. Can someone please advise how to terminate or timeout the telnet command using shell script once it is executed.

telnet_output=`telnet $server $port`
echo "Output is $telnet_output"

I tried writing it to a file as well. But this is also getting hung when executed in remote server.

opfile="telop.log"
telnet_output=`telnet $server $port | tee $opfile`
op=`cat $opfile`
echo "$op"

Solution

Try this :

telnet_output="$({ sleep 1; echo $'\e'; } | telnet $server $port 2>&1)"
printf "Output is\n%s\n" "$telnet_output"

echo $'\e' sends an escape character to telnet to terminate it.



Answered By - Philippe