2014-02-27 119 views
2

嗨最好的方法是检查SSH是否因任何原因失败? 我可以使用IF语句(如果它失败,然后做点什么) 我在一个循环中使用ssh命令,并将我的主机名称传递给一个平面文件。在脚本中检查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不被允许或我没有正确的密码?

请多关照 干杯

回答

3

您可以检查返回值ssh在给你最初如下所示: How to create a bash script to check the SSH connection?

$ ssh -q [email protected] exit 
$ echo $? 
255 

$ ssh -q [email protected] 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 
+0

好THX wbt11a ..我知道如何捕获,但在SSH comman的背景下d我发布了如何做到这一点?我需要在这个命令的同一个传递中为我在'cat/tmp/hosts'中使用它;做ssh $ i'hostname; sudo ethtool eth1';完成 – theuniverseisflat

+0

嗨,感谢我的一半通过。但是我仍然收到4个无法访问的密码主机的提示。我怎样才能跳过这些主机?基本上有办法逃避密码挑战,并跳转到下一个主机? – theuniverseisflat

+0

尝试在示例中看到'-o'BatchMode = yes''标志。 – wbt11a

5

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

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 
+0

好Thx“ThatOtherGuy”..我知道如何陷阱,但在我发布的ssh命令我该怎么做?我需要在这个命令的同一个传递中为我在'cat/tmp/hosts'中使用它;做ssh $ i'hostname; sudo ethtool eth1';完成 – theuniverseisflat

+0

@theuniverseisflat请参阅更新 –

+0

谢谢我的一半。但是我仍然收到4个无法访问的密码主机的提示。我怎样才能跳过这些主机?基本上有办法逃避密码挑战,并跳转到下一个主机? – theuniverseisflat