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?
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)
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!
Redirect the output to a file and read from the file
telnet [ip-address] > /tmp/tempfile.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With