bashtelnet

How to get telnet output to a variable?


I have a Bash script which sends a value using telnet and receive some data back. How can I put the data I received into a variable?

Manually when I run the commands i get the following results.

$telnet 192.168.11 12345
>> 5 :234568
>>Adjust:False,offset 0

The first line is my input and the second line is the response I receive. I want to assign this response to a variable. In the bash script I tried using,

    response=$(echo -e "$message" | telnet "$TELNET_SERVER" "$TELNET_PORT" 2>&1)
    echo "Response from server: $response"

while it managed to send the data ("message") successfully. I couldn't get the response assigned to a variable. While tried running the command in terminal, the output is empty.

Can anyone give me some solution? Thank you.


Solution

  • You can use the TCP/IP stack of bash instead of telnet:

    #!/bin/bash
    
    TELNET_SERVER=192.168.1.1    # shall be an IP address (not a DNS)
    TELNET_PORT=5000
    message='5 :234568'
    
    exec 3<>/dev/tcp/"$TELNET_SERVER"/"$TELNET_PORT"
    
    echo -e "$message" >&3
    
    IFS= read -r -u3 -t1 response
    
    exec 3<&-
    

    There's a few shortcomings with this method though:

    1. If the response is expected to span multiple lines then you'll have to use a while read loop instead of just a single read.

    2. If the response takes more time to arrive than the specified timeout (here it is -t 1 second) then the read will be aborted. I have to say that specifying a timeout is absolutely necessary; without it the read could hang indefinitely.