user1336117
user1336117

Reputation: 451

Linux script to parse telnet message and exit

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?

Upvotes: 9

Views: 25332

Answers (4)

Seff
Seff

Reputation: 1817

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)

Upvotes: 11

user3523425
user3523425

Reputation:

Already answered, but here's another point of view using curl, useful for quick checks (ie service active or not). I had to struggle a bit avoiding "script" and "expect" solutions.

Just a stub for possible POP3 check:

echo "quit" | curl telnet://localhost:110 > /tmp/telnet_session.txt
if grep "POP3 ready" /tmp/telnet_session.txt; then
        echo "POP3 OK"
else
        echo "POP3 KO"
fi

Upvotes: 1

dAm2K
dAm2K

Reputation: 10339

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!

Upvotes: 6

siva
siva

Reputation: 1145

Redirect the output to a file and read from the file

telnet [ip-address] > /tmp/tempfile.txt

Upvotes: 1

Related Questions