0

I am creating one bash script which can automate the process of checking the connectivity between two unix hosts. Need to check whether specific port is open from one host to other. hosts don't have NCAT(due to some constraint) so have to use Telnet only.

Code works fine if telnet connection is successful however takes more then 2 minutes if telnet fails. I need telnet to exit within 2 secs if it is not connecting. Trying to find a way to force the telnet command to exit even if it fails.

I have created couple of scripts which can read source file and run below command from there to telnet the destination servers.

Below code will be executed on the server from where telnet connectivity needs to be tested.

#!/usr/bin/bash
>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
echo "Checking Telnet connection from "$1 >>/wastmp/$1.txt
echo "********************************************************************" >>/wastmp/$1.txt
while read target;
do
x=$(sleep 3 | telnet `echo  $target | awk 'BEGIN { FS=":" } { print $1 }'` ` echo  $target | awk 'BEGIN { FS=":" } { print $2 }
'` | grep -i connected | awk  {'print $1'})
if [[ "$x"  ==  "Connected" ]];
  then
   echo $target"=Success" >>/wastmp/$1.txt
  else
   echo $target"=Fail, please check server & port">>/wastmp/$1.txt
fi
done </wastmp/target_server

Expected result: host1:port=Fail, please check server & port host2:port=Fail, please check server & port . . .

hostn:port=Success

rblock
  • 58
  • 5
Rahul
  • 1
  • You could look at trying to use a utility such as the one found here, https://elifulkerson.com/projects/tcping.php, since it is a ping that can use port numbers. – Jim Grant May 28 '19 at 14:45
  • General answer , to force timeout any shell command you can prefix it with `timeout` to timeout that command in provided time. for example `timeout 5 telnet 1.3.4.5` will auto timeout in 5 seconds unless telnet return before 5 seconds. note that `rc` will be non-zero when command is exited by `timeout` command. – P.... May 28 '19 at 14:53
  • adding timeout before the command works for me. Thanks – Rahul Jun 20 '19 at 12:13

1 Answers1

0

You need to send telnet a exit. Another reason it lags is that pipe line of redundant awk commands.

This is how i would write the x variable:

x=$(echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected")

The condition could also be shortened to:

echo exit 0 | telnet $target 2>/dev/null | grep -o "Connected" 1>/dev/null && echo "Success" >>/wastmp/$1.txt  || echo "Failed" >>/wastmp/$1.txt
goose goose
  • 86
  • 3
  • 15