Score:0

How to script a check that the key in known_hosts file is correct

tr flag

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?

Score:1
vn flag
#!/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"
Score:0
us flag

If you have list of all hosts available you can use the below:

ssh-keyscan -t rsa,dsa -f hosts_list > ~/.ssh/known_hosts_revised

This will generate a new known_hosts_revised which you can use to make a diff with current know_hosts to see the differences.

The hosts_list content should be like:

1.2.3.4,1.2.4.4 name.my.domain,name,n.my.domain,n,1.2.3.4,1.2.4.4
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.