-2

I'm writing a bash script that goes through a for loop which is a list of each hostname, then will test each one if it's responding on port 22, if it is then execute an ssh session, however both the first and second if statements are only executed on the first host in the list, not the rest of the hosts. If the host isn't responding on port 22, I want the script to continue to the next host. Any ideas how to ensure the script runs the ssh on each host in the list? Should this be another for loop?

#!/bin/bash

hostlist=$(cat '/local/bin/bondcheck/hostlist_test.txt')


for host in $hostlist;  do

test=$(nmap $host -P0 -p 22 | egrep 'open|closed|filtered' | awk '{print $2}')

        if [[ $test = 'open' ]]; then

                        cd /local/bin/bondcheck/
                        mv active.current active.fixed
                        ssh -n $host echo -n "$host: ; cat /proc/net/bonding/bond0 | grep Active" >> active.current

                        result=$(comm -13 active.fixed active.current)

                if [ "$result" == "" ]; then
                                exit 0
                else
                        echo "$result" | cat -n
                fi

        else
                echo "$host is not responding"
        fi
done
Mathews Jose
  • 399
  • 6
  • 18
  • Mind that in later versions of nmap `-P0` is same as `-Pn`. – sjsam Jun 29 '16 at 16:42
  • Also, your `test=$(nmap $host -P0 ...` line may be replaced by `test=$(nmap $host -P0 -p 22 | awk '/^22\/tcp/{print $2}'` – sjsam Jun 29 '16 at 16:48

2 Answers2

3

exit 0 exits the entire script; you just want to move on to the next iteration of the loop. Use continue instead.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

You problem is most likely in the lines

if [ "$result" == "" ]
then
 exit 0
else
 echo "$result" | cat -n
fi

Here the exit 0 causes the entire script to exit when the $result is empty. You could the way around using :

if [ "$result" != "" ] #proceeding on non-empty 'result'
then
 echo "$result" | cat -n
fi
sjsam
  • 21,411
  • 5
  • 55
  • 102