SSH Scripting – How to Script a Check That the Key in Known_hosts File Is Correct

scriptingssh

I would like to implement a function in a script that checks if the key that corresponds to a given host in known_hosts file is correct. The obvious way to do this is to attempt an ssh connection and parse if it results in the known_hosts warning. This is suboptimal for these reasons:

  • If the host is not in the know_hosts file it needs to be checked separately
  • It relies on a particular wording of the warning that is subject to change
  • It runs an ssh command for you on the target server that you do not need to run and which could fail for different reasons such as what login shell is specified
  • Requires valid credentials

I tried to find an option in ssh-keyscan and ssh-keygen commands that might to that check, but did not find them.

What is the simplest way to do this check?

Best Answer

#!/usr/bin/env bash

HOST=$1

set -o pipefail

HOST_KEY_LINE=$(ssh-keygen -F "$HOST" | tail -n1)

if [ $? -ne 0 ]; then
  echo "$HOST is not in the known_hosts file"
  exit 1
fi

KEY_TYPE=$(echo "$HOST_KEY_LINE" | awk '{ print $2 }')
HOST_KEY=$(echo "$HOST_KEY_LINE" | awk '{ print $3 }')

ACTUAL_KEY=$(ssh-keyscan -t "$KEY_TYPE" "$HOST" 2>&1 | tail -n1 | awk '{ print $3 }')

if [ $? -ne 0 ]; then
  echo "Could not get key from $HOST: $ACTUAL_KEY"
  exit 1
fi

if [ "$HOST_KEY" = "$ACTUAL_KEY" ]; then
  echo "known_hosts has a correct key"
  exit 0
fi

echo "known_hosts has an incorrect key"