MLSC
MLSC

Reputation: 5972

best way to get the result of `$?` for telnet connections

I want to telnet some ips and I want to get the result of $? immediately: SO I tried:

while read ip; do
    telnet $ip 1>/dev/null 2>&1
    pkill $!
    if [ "$?" -eq "1" ]; then
       echo $ip >> host-ok
    fi
done < file

But this is not a good idea because when a telnet connection can't be established it doesn't work. and always the out put of $? would be correct.

I want to be sure telnet is going to be established and then kill the process. So if telnet is established after that I want to echo $ip to a file.

Any other solutions are welcome

Thank you

Upvotes: 0

Views: 410

Answers (3)

MLSC
MLSC

Reputation: 5972

This is the fastest and the most reliable solution in the eyes of me:

LIST=$1
while read ip;do
    echo "exit" | nc "$ip" 23 -w 5
    if [ "$?" -eq "0" ]; then
        echo "$ip" >> host-ok
    fi
done < $LIST

Using nc rather than telnet is faster.

Upvotes: 0

l0b0
l0b0

Reputation: 58928

The code as written doesn't work because the telnet command is not backgrounded - pkill $! will always fail, because process $! no longer exists when you reach that line. You need to append an ampersand & at the end of the line to do that. You also need a timeout before killing the process, otherwise it won't have time to try to connect before stopping it. sleep 1 (or 5, or 60, depending on your use case) should take care of that.

You also want to use kill rather than pkill.

An alternative method which is probably much more robust is to avoid the killing altogether, and simply try to connect and quit immediately (similar to @PeteyT's answer):

while read ip; do
    printf '%bquit\n' '\035' | telnet "$ip" 1>/dev/null 2>&1
    if [ $? -eq 0 ]; then
       echo "$ip" >> host-ok
    fi
done < file

That should use the telnet default timeout (I don't know how long that is). If you want a configurable timeout you could try netcat.

Upvotes: 2

ptierno
ptierno

Reputation: 10064

 while read ip; do
   printf '%bquit\n' '\035' | telnet $ip 1>/dev/null 2>&1
   kill $!
   if [ $? -eq "1" ]; then
     echo $ip >> host-ok
   fi
 done < file

Upvotes: 1

Related Questions