Search code examples
linuxshellconnection

How to add multiple host in shell script


I am trying to run below script & it's working fine for one host but I want to add multiple host.

host=1.2.3.4
LOG_OK=/tmp/port-check-success.log
LOG_FAIL=/tmp/port-check-failed.log

for port in 80 443
do
if telnet -c $host $port </dev/null 2>&1 | grep -q Escape; then
  echo  "$port: Connected" >> $LOG_OK
else
  echo "$port : no connection" >> $LOG_FAIL
fi
done

Solution

  • Just have a for loop for host in the same way that you are already doing for port, and nest one loop inside the other. For example:

    LOG_OK=/tmp/port-check-success.log
    LOG_FAIL=/tmp/port-check-failed.log
    
    for host in 1.2.3.4 5.6.7.8
    do
        for port in 80 443
        do
            if telnet -c $host $port </dev/null 2>&1 | grep -q Escape; then
                echo "$host: $port: Connected" >> $LOG_OK
            else
                echo "$host: $port : no connection" >> $LOG_FAIL
            fi
        done
    done