bash 在脚本中检查 SSH 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22078806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:44:11  来源:igfitidea点击:

Checking SSH failure in a script

bashloopssshruntime-error

提问by theuniverseisflat

Hi what is the best way to check to see if SSH fails for whatever reason? Can I use a IF statement ( if it fails then do something) I'm using the ssh command in a loop and passing my hosts names form a flat file.

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

so I do something like:

所以我做这样的事情:

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

I get sometime this error or I just cannot connect

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

ssh: host1 Temporary failure in name resolution

I want to skip the hosts that I cannot connect to is SSH fails. What is the best way to do this? Is there a runtime error I can trap to bypass the hosts that I cannot ssh into for whatever reason, perhaps ssh is not allowed or I do not have the right password ?

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

Thanking you in advance Cheers

提前致谢

采纳答案by wbt11a

You can check the return value that ssh gives you as originally shown here: How to create a bash script to check the SSH connection?

您可以检查 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

EDIT - I cheated and used nc

编辑 - 我作弊并使用了 nc

Something like this:

像这样的东西:

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

回答by that other guy

To check if there was a problem connecting and/or running the remote command:

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

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

To check if there was a problem connecting, regardless of success of the remote command (unless it happens to return status 255, which is rare):

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

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

Applied to your example, this would be:

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

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