Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking SSH failure in a script

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.

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 ?

Thanking you in advance Cheers

like image 251
theuniverseisflat Avatar asked Feb 27 '14 19:02

theuniverseisflat


People also ask

How do I SSH a script?

An SSH script can be configured as a dependency of a Secret and run after the password is successfully changed on the Secret. From the Administration Menu, click Scripts. Click the SSH tab on the Scripts page, then click the Create New button. Enter the "Name", "Description", and "Script" in the dialog then click OK.

Can I SSH in a bash script?

Bash script SSH is a common tool for Linux users. It is needed when you want to run a command from a local server or a Linux workstation. SSH is also used to access local Bash scripts from a local or remote server.


Video Answer


2 Answers

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):

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
like image 184
that other guy Avatar answered Nov 01 '22 22:11

that other guy


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 -q user@downhost exit
$ echo $?
255

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

EDIT - I cheated and used 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
like image 37
wbt11a Avatar answered Nov 01 '22 23:11

wbt11a