0

I am trying to check that an SSH connection succeeds (while running a script).

I am trying to use the answer from here, but the unsuccessful connection returns an error code of 0.

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

I have tried a variety of invalid ssh commands but they all return a 0 return code; making it hard to check for failure.

I feel I must be doing something wrong, but can't work it out. Is there some setting that I have changed maybe?

I am running CentOS 7, with the following SSH version:

$ ssh -V
OpenSSH_6.6.1p1, OpenSSL 1.0.1e-fips 11 Feb 2013
Community
  • 1
  • 1
Mark Perryman
  • 749
  • 7
  • 18
  • Did you try the other answers, for example running `ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1` ? which will `ok` on successful login. – Inian Jan 26 '17 at 17:35
  • 1
    `ssh -q user@downhost exit` Why are you expecting this command to fail? Do you understand that in the other question, "downhost" is supposed to represent a host that's not accessible at the time? – Kenster Jan 26 '17 at 18:18
  • @Inian, I could possibly hack something together from that answer (running in a subshell maybe?), but I want this to be the condition of an ``if`` statement, so the return code seemed the place to look. – Mark Perryman Jan 27 '17 at 09:27
  • @Kenster. I have tried it with an uncontactable IP address, a non-existent hostname and a hostname that fails host key checking. I remain confused. I was expecting the command to fail unless it successfully connected. – Mark Perryman Jan 27 '17 at 09:31

1 Answers1

-1

I remain confused as to why the example is failing, but the following seems to be working for me.

can_connect_ssh()
{
    HOST=$1
    ssh -q -o BatchMode=yes -o ConnectTimeout=5 $HOST echo connection_success | \
       grep connection_success &> /dev/null
}

Called as:

if can_connect_ssh <hostname>; then
    echo "Successful Connection"
else
    echo "Failed Connection"
fi
Mark Perryman
  • 749
  • 7
  • 18
  • 3
    I doubt very much that works for you. I think you meant to omit the `return` keyword from `can_connect_ssh`. – chepner Jan 27 '17 at 16:02