How to check connection to a list of servers in bash?

Viewed 1363

Im trying to check connections for a list of servers. I want to loop through the list, check if a connection works and if yes, do some stuff, if not, echo out a problem message.

My problem is:
the script stops at the first node without echoing the $?. So, whats wrong with my for-loop?

These vars are included from a config file:
$nodes is a list of server IPs like 1.1.1.1,2.2.2.2,10.10.10.10
$user is one string

for node in $(echo $nodes | sed "s/,/ /g")
    do
    echo "Checking Node: $node"

    ssh -q -o ConnectTimeout=3 $user@$node echo ok
    echo $?
    if [[ $? != 0 ]]
    then
        echo "Problem in logging into $node"
    else
        # do some stuff here
    fi
done

EDIT #1:

for node in $(echo $nodes | sed "s/,/ /g")
    do
    echo "Checking Node: $node"

    ssh -q -t -o ConnectTimeout=3 $user@$node "echo ok"
    retcode=$?
    echo $retcode
    if [[ "$retcode" -ne 0 ]]
    then
        echo "Problem in logging into $node"
    else
        echo "OK"
    fi
done
2 Answers

You can add -tto make virtual terminal and add quotes on command:

ssh -q -t -o ConnectTimeout=3 ${user}@${node} "echo ok"

Also use -ne instead of != which is for compare strings

if [[ "$?" -ne 0 ]]

Also echo $? mess the return code. You should use something like:

ssh -q -t -o ConnectTimeout=3 ${user}@${node} "echo ok"
retcode=$?
echo $retcode
if [[ "$retcode" -ne 0 ]]

You can rewrite ssh command like this to avoid problems with ssh host keys

ssh -q -t -o StrictHostKeyChecking=no -o ConnectTimeout=3 ${user}@${node} "echo ok"

It is because ssh first asks you to validate The authority of the host and If you accept the authority it will ask for password. That is why your command does not return to shell and waits for input.

If your intention is just validating ssh connection, then you may consider to use

telnet <your_host> <port> < /dev/null

But if your intend is to run some commands you need a trust relationship between hosts. In that case you can use:

Execute this commands:

ssh-keygen -t rsa

then

ssh-copy-id -i root@ip_address

Now you can connect with

ssh <user>@<host>

Furher information

Related