linuxgreptelnet

use grep to find a word in the output from telnet connection


I would like to use telnet to connect to a system and check if foreign is in the response.

I am trying ...

echo quit | telnet 192.0.0.1 443 | grep -q "foreign"

In that a successful connection means "foreign" was found in the string. This is because in the output I get something like...

Trying 192.0.0.1
Connected to 192.0.0.1
Connection closed by foreign host

But if I check echo $? I get a 1 indicating it failed to find the word. My guess is that this is due to the multiple line output.

Is there a way to handle this so I get 0 from echo $??

Must be done via terminal - no scripts etc.

And must be telnet


Solution

  • What I would do:

    { sleep 1; echo quit; } | telnet 192.0.0.1 443 2>&1 | grep -q "foreign"
    

    or with bash:

    { sleep 1; echo quit; } | telnet 192.0.0.1 443 |& grep -q "foreign"
    

    With retry:

    until [[ $out == *foreign* ]]; do
        out=$({ sleep 1; echo quit; } | telnet 192.0.0.1 443 |& grep "foreign")
        sleep 1
    done