Tuesday 10 January 2017

Automating telnet prompts in shell scripts


Telnet is a common tool we use to confirm if connectivity on a particular port is working or not.
However, since it's an interactive program it's difficult to use it in a script.
Since you have to press ctrl+] followed by quit every time you exit the telnet prompt.

I found a neat little trick to get around this using echo command.
If we pipe the word quit to our telnet test then the telnet prompt exits automatically once the test concludes.

[ssuri@:~] $ echo "quit" | telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection to localhost closed by foreign host.


This can prove to be very helpful while writing scripts.
For example, if want a particular action to be performed if connectivity exists & the code should exit otherwise.
One thing I couldn't get around is that "Connection to localhost closed by foreign host." printed no matter what text filter I tried.
So, I finally did a workaround by redirecting the telnet test output to a file & then running an if condition on the file.

Given below is the example:


#!/usr/bin/bash

VAR1=$(echo "quit" | telnet localhost 25 | awk 'NR==2 {print $1}')

echo  $VAR1 > /tmp/sa

VAR2=$(cat /tmp/sa)

if [ $VAR2 == "Connected" ] ; then
        echo "connectivity exists"
fi

rm /tmp/sa


This script provides the following output when executed.

[ssuri@:~] $ bash def.sh
Connection to localhost closed by foreign host.
connectivity exists

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...