【问题标题】:Checking SSH failure in a script在脚本中检查 SSH 失败
【发布时间】:2014-03-31 11:45:18
【问题描述】:

您好,检查 SSH 是否因任何原因失败的最佳方法是什么? 我可以使用 IF 语句(如果它失败然后做某事) 我在循环中使用 ssh 命令并将我的主机名传递给一个平面文件。

所以我做了类似的事情:

for i in `cat /tmp/hosts` ; do ssh $i 'hostname;sudo ethtool eth1'; done

我有时会收到此错误,或者我无法连接

ssh: host1 Temporary failure in name resolution

如果 SSH 失败,我想跳过无法连接的主机。做这个的最好方式是什么?是否存在运行时错误,我可以捕获以绕过由于某种原因无法 ssh 进入的主机,可能是不允许 ssh 或我没有正确的密码?

提前感谢您 干杯

【问题讨论】:

    标签: bash loops ssh runtime-error


    【解决方案1】:

    检查连接和/或运行远程命令是否有问题:

    if ! ssh host command
    then
      echo "SSH connection or remote command failed"
    fi
    

    检查是否有连接问题,无论远程命令是否成功(除非它恰好返回状态 255,这种情况很少见):

    if ssh host command; [ $? -eq 255 ]
    then 
      echo "SSH connection failed"
    fi
    

    应用于您的示例,这将是:

    for i in `cat /tmp/hosts` ;  
    do 
      if ! ssh $i 'hostname;sudo ethtool eth1'; 
      then 
        echo "Connection or remote command on $i failed";
      fi
    done
    

    【讨论】:

    • Ok Thx "ThatOtherGuy" .. 我知道如何进行陷阱,但在我发布的 ssh 命令的上下文中,我该怎么做?我需要在 cat /tmp/hosts 中的 i 的同一命令中使用它;做 ssh $i '主机名;sudo ethtool eth1';完成
    • 谢谢,我完成了一半。但我仍然收到提示 4 个我无权访问的密码主机。我怎样才能跳过这些主机?基本上有没有办法逃脱密码挑战并跳转到下一个主机?
    【解决方案2】:

    您可以检查 ssh 为您提供的返回值,如下所示: How to create a bash script to check the SSH connection?

    $ ssh -q user@downhost exit
    $ echo $?
    255
    
    $ ssh -q user@uphost exit 
    $ echo $?
    0
    

    编辑 - 我作弊并使用了 nc

    类似这样的:

    #!/bin/bash
    ssh_port_is_open() { nc -z ${1:?hostname} 22 > /dev/null; }
    
    for host in `cat /tmp/hosts` ; do
        if  ssh_port_is_open $host; then
            ssh -o "BatchMode=yes" $i 'hostname; sudo ethtool eth1';
        else
            echo " $i Down"
        fi
    done
    

    【讨论】:

    • Ok Thx wbt11a .. 我知道如何进行陷阱,但是在我发布的 ssh 命令的上下文中,我该怎么做?我需要在 cat /tmp/hosts 中的 i 的同一命令中使用它;做 ssh $i '主机名;sudo ethtool eth1';完成
    • 嗨,谢谢,我完成了一半。但我仍然收到提示 4 个我无权访问的密码主机。我怎样才能跳过这些主机?基本上有没有办法逃脱密码挑战并跳转到下一个主机?
    • 试试例子中看到的 '-o "BatchMode=yes"' 标志。
    • 如果 [ ! ssh -o $1 ] ;然后 echo sshfailed else echo 仍然挑战我
    • 嗨试过了,但它在某处失败了?你能帮忙..如果[! ssh -o $1 ] ;然后 echo sshfailed else echo 挑战我仍然 fi
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2015-10-10
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多