I am using below code for to telnet the multiple servers.

while read line
  ip=$( echo "$line" |cut -d ' ' -f 1 )
  port=$( echo "$line" |cut -d ' ' -f 2 )
  if  telnet  $ip $port </dev/null 2>&1 | grep -q Escape 
    echo "$ip $port Connected" >> Telnet_Success.txt
  elif  telnet  $ip $port </dev/null 2>&1 | grep -q refused 
    echo "$ip $port Refused" >> Telnet_Refused.txt
    echo "$ip $port Failed" >> Telnet_Failure.txt
done < ${file}

with input file as txt enter image description here and the expected output is enter image description here and I am getting output as enter image description here I need to write a script to get the expected output.

  • 1
    Hi Umesh, could you, please edit your question and reformat it without pasting text as images ? Also, please let us know what your question is : what are you trying to achieve (give examples, please) ? What's the output so far ? – Httqm May 22 at 15:32
  • I am trying to do the telnet using ip and port , IP and Port are reading from text file. when i am using above code it is reading first line item of IP and port from text file. if there are multiple line items it is not giving the results as expected. I given screenshot for better understanding. – Umesh May 22 at 15:40

I am unclear why you wish to create three output files but since it is your requirement and not mine, perhaps the following will help.

data=${1:-ip.txt} while read host port; do preamble="telnet $host $port" case $(telnet $host $port </dev/null 2>&1 | tail -1) in (*closed*) echo "$preamble ... Connected" >>Telnet_Success.txt ;; (*refused*) echo "$preamble ... Refused" >>Telnet_Refused.txt ;; (*) echo "$preamble ... Failed" >>Telnet_Failure.txt esac done <$data exit

The first line allows you to decide to give the input data in another file (e.g. data.txt) by providing that as an argument to the script. For example

$ telnet.sh data.txt

If this is not given it will assume the file 'ip.txt'. Then use a case statement to match the last line of the command output to determine the file in which the result message is placed.

Note that the read statement allows you to pick up separate "words" on the input line -- thus removing the need for the use of commands like cut here. Also the way you have used your files means that succeeding runs of the script are added to existing output lines. That may not be what you want.


P.S. Strictly speaking I should have placed a shebang line at the top as in: #!/bin/sh or similar. I relied here on the fact that I am running on a Linux system with a Bash shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.