bash ssh到服务器列表

时间:2015-08-09 11:47:27

标签: bash ssh

我想在列表中给出的主机之间进行ssh。我得到了下面的脚本,我觉得有效(我无法登录他们,我用回声来确定)。

唯一的问题是在第二个' for'循环,它保持ssh到第一个主机;然后ssh到其余的。我希望它ssh到一个服务器,然后从那里ssh到其余的。 有什么建议吗?

#!/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"

1 个答案:

答案 0 :(得分:1)

您可以将内部循环放在here doc中,但请确保转义要在远程计算机上展开的任何变量。你可以这样做:

#!/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