Check SSH connections

March 17, 2020

The other day, I needed to check if all servers I supervised were available to SSH. I added every droplet from Digital Ocean to my config file at ~/.ssh/config.

But then manually checking every entry was pretty long and boring. Anyway, doing it manually was not a solution as I want the capability to quickly check my access-state to the servers. So here comes a terminal approach to automate the process.

First create a bash script test-ssh.sh and chmod +x test-ssh.sh

#!/bin/bash

HOST=$1
echo "> $HOST..."

ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no $HOST 'exit 0'
RCODE=$?
if [ $RCODE -ne 0 ]; then
        echo "  [!] Unable to ssh on: $HOST"
else
        echo "OK"
fi

This script takes in argument the Hostname and checks if it is possible to connect. With the ssh line, I use the quiet mode (-q) to keep it short, and the Bash Mode which tells SSH to never ask for a passphrase or password. The StrictHostKeyChecking is used to bypass the fingerprint verification process.

Then, to loop through the config file, I use this bash line:

$ cat ~/.ssh/config | grep "Host " | awk '{print $2}' | xargs -I _ ./test-ssh.sh _

awk retrieves the Hostname from the grep output and then passes it to xargs which injects it to the bash script through the -I flag. -I specify a character ('_' in our case) to indicate where to inject the input.

The output is the following:

> service-notifications-corona...
OK
> olympe-12-was8...
  [!] Unable to ssh on: olympe-12-was8
> microservice-api-27...
OK

Making sure I can connect to those servers improves my time-to-react in case of problems.