Search code examples
bashshelltestingshtelnet

Shell Script - telnet multiple hosts:ports


I'm not an expert in shell script by any means. I got the structure idea from another post (Bash script telnet to test multiple addresses and ports) My need is to verify LAN connections between specific hosts and ports via telnet.

The reason for using telnet is the fact that both the LAN and machines are heavily secure and I don't have access to netcat, nmap or /dev/tcp. I'm also no where near comfortable with Python or Pearl to try that route... ( I know silly me, I'll get there though :P ).

The following code works, however for reasons beyond my understanding the while loop iterates only once and no more... :( .

Note: it is important for me to know if the connection failed due to timeout or was refused (port is closed at the endpoint).

Can anyone help me in 1) fixing it and 2) understanding why?

FYI: For anyone else that might have a similar need here's the fully operational updated code for the script. In this case connection refused is being handled as a success (testing firewall rules) which can be changed to failed depending on necessities.

    #!/bin/bash
    path=`pwd`;
    touch $path/test_telnet.out || exit;
    touch $path/success.log || exit;
    touch $path/failed.log || exit;
    echo "10.192.168.1 1200
    10.10.10.2 80
    10.220.2.8 6090
    10.220.2.9 6090" | ( while read host port; do
        telnet $host $port </dev/null > $path/test_telnet.out 2>&1 & sleep 1; kill $!;
        if grep Connected $path/test_telnet.out >/dev/null;
            then
                echo @ $(date +"%b %d %H:%M %Y") $host:$port [ OPEN ] | tee -a $path/success_log.txt;
            elif grep refused $path/telnet_test.txt >/dev/null; then
                echo @ $(date +"%b %d %H:%M %Y") $host:$port [ REFUSED ] | tee -a $path/success_log.txt;
            else
                echo @ $(date +"%b %d %H:%M %Y") $host:$port [ TIMEOUT ] | tee -a $path/failed_log.txt;
        fi;
    cp /dev/null $path/test_telnet.out;
    done
    ) 2>/dev/null #avoid bash messages

Solution

  • As Etan commented, telnet is eating the rest of your input. The fix is to redirect the input for telnet.

    Change this:

    telnet $host $port > ~/test_con/telnet_test.txt
    

    to this:

    telnet $host $port </dev/null > ~/test_con/telnet_test.txt