0

I'm trying to connect to multiple hosts to check config files for various things like ldap and dns servers being used. My end goal is to just give it a list of hosts (preferably a file outside of the script), and whatever $SCRIPT I want it to run, and dump it to a file to check for errors. It connects to the first host fine, outputs to file fine, but then just stops, and won't connect to subsequent hosts, namely, app-03.

#!/bin/bash
HOSTS="app-01.stage app-03.stage"
SCRIPT1="hostname"
SCRIPT2="grep ldp-02 /etc/ldap.conf"
SCRIPT3="cat /etc/resolv.conf"
FILE="test.txt"
for HOSTNAME in ${HOSTS} ;
    do 
    ssh -o "StrictHostKeyChecking no" -n $HOSTNAME "$SCRIPT1; $SCRIPT2; $SCRIPT3"
        if [ "$?" = 1 ]; then
            echo "FAIL - could not connect"
        else
    exit
    fi 
done >> $FILE

1 Answer 1

1

exit does exactly what it sounds like: it exits the script, so your script is done before the second iteration is reached. I think you just want something like

for HOSTNAME in ${HOSTS} ;
do 
    ssh -o "StrictHostKeyChecking no" -n $HOSTNAME "$SCRIPT1; $SCRIPT2; $SCRIPT3"
    if [ "$?" = 1 ]; then
        echo "FAIL - could not connect"        
    fi 
done >> $FILE

If $? is not 1, you don't need to do anything, and the loop will move on to the next host.

Assuming you are just interested in a non-zero exit code, rather than 1 (as opposed to 2 or 3 or some other code), you can write the if statement more idiomatically as

if ! ssh -o "StrictHostKeyChecking no" -n "$HOSTNAME" "$SCRIPT1; $SCRIPT2; $SCRIPT3"; then
    echo "FAIL - could not connect
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.