Sam Pinar
Sam Pinar

Reputation: 43

bash ssh to a list of servers

I want to ssh between hosts given in a list. I got below script which I think works (I can't login to them, I use the echo's to determine).

The only issue is that in the second 'for' loop, it keeps ssh'ing to the first host; then ssh's to the rest. I want it to ssh to one server, then ssh to the rest from there. Any suggestions?

#!/bin/bash

hosts='host1 host2 host3 host4 host5 host6 host7'
sup='sup!123'

for i in $hosts; do
    echo "***** We are: $i *******"

    for d in $hosts
    do
        echo "******** Logging in from $i to: $d *********"
        ssh -t $i "ssh $d exit"

        if [ $? = 0 ]; then
            echo "SSH login successful!"
        else
            echo "SSH login failed!"
        fi
    done
    echo "Finished block for $i"

Upvotes: 0

Views: 1224

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14500

You could put the inner loop in a here doc, but make sure to escape any variables you want to have expanded on the remote machine. You could do it like this though:

#!/bin/bash

hosts='fry nashua north'
sup='sup!123'

for i in $hosts; do
   echo "***** We are: $i *******"

    ssh -t $i <<EOCommand
        for d in $hosts
        do
            echo "******** Logging in from $i to: \$d *********"
            ssh \$d exit

            if [ $? = 0 ]; then
                echo "SSH login successful!"
            else
                echo "SSH login failed!"
            fi
        done
EOCommand
    echo "Finished block for $i"
done

Upvotes: 1

Related Questions