Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux script to parse telnet message and exit

Tags:

linux

bash

telnet

I am connecting to a telnet listener. Telnet server sends "1234" for every second. I want to read the message "1234" and close the telnet session. Here below is my code but it does not work.

#!/bin/bash
telnet 192.168.10.24 1234
read $RESPONSE
echo "Response is"$RESPONSE
echo "quit"

How can i automatically read the telnet message?

like image 881
user1336117 Avatar asked Apr 16 '12 11:04

user1336117


3 Answers

The simplest and easiest method is given below.

sleep <n> | telnet <server> <port>

n - The wait time in seconds before auto exit. It could be fractional like 0.5. Note that some required output may not be returned in the specified wait time. So we may need to increase accordingly.

server - The target server IP or hostname.

port - Target service port number.

You can also redirect the output to file like this,

sleep 1 | telnet <server> <port> > output.log

Update 1#: The above method may not works if the remote host doesn't accept nor drops the connection request. In those case, the following method works:

RESPONSE=$(timeout 5 telnet 192.168.10.24 1234)
like image 99
Seff Avatar answered Oct 13 '22 21:10

Seff


You could use internal TCP mechanism:

#!/bin/bash

exec 3<>/dev/tcp/127.0.0.1/80
# echo -en "eventualy send something to the server\n" >&3
RESPONSE="`cat <&3`"
echo "Response is: $RESPONSE"

Or you could use nc (netcat), but please don't use telnet!

like image 41
dAm2K Avatar answered Oct 13 '22 22:10

dAm2K


Redirect the output to a file and read from the file

telnet [ip-address] > /tmp/tempfile.txt
like image 30
siva Avatar answered Oct 13 '22 23:10

siva