Test An SSH Connection

In a script I was writing earlier this afternoon I needed a quick way to test an SSH connection for full functionality. Full functionality being the ability to actually login and use the service as opposed to the port simply being open.

I stumbled across this one liner and incorporated it into my script:

ssh -q -o “BatchMode=yes” user@host “echo 2>&1″ && echo “Up” || echo “Down”

Lets break it down.

ssh -q

The -q option tells SSH to suppress it’s output.

-o “BatchMode=yes”

As defined by man ssh_config batch mode means:

If set to “yes”, passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present to supply the password. The argument must be “yes” or “no”. The default is “no”.

&& echo “Up” || echo “Down”

The && means that if our ssh connection completes and exits correctly it will echo “Up”. The || stands for OR, if the login did not complete successfully it will execute the code behind it, in this case echo “Down”

This is a nifty one liner to keep in your toolbox, you can do a lot with the concepts inside of it. The next time you need to test a connection try using the same logic, its transferable to almost any service. Something else to think about is setting up ssh keys so the entire process is as painless as possible, I tend to do this whenever I build a new box.