1

ssh-keygen -R $HOSTNAME can remove the ssh host key(s) from one's known_hosts. Can I add a specific host key (for a hostname/ip) to a known_hosts in an idempotent way?

I want to script ssh'ing into a server. This might be run by someone who has not ssh'ed into that server before, and hence the server's host key would not be in the known_hosts file, so they would be asked to accept it. I would like to remove this step, to make everything streamlined. How can I do this?

ssh -o StrictHostKeyChecking=no … disabled that sercurity, which has downsides. ssh-keyscan $HOSTNAME > ~/.ssh/known_hosts will work, but the known_hosts file will constantly grow, and will update the file with the current host key. Is there a way to do this idempotently, for a fixed, defined servername & host key combo? i.e. “If you don't have $HOST_KEY for $HOSTNAME, add that to your known_hosts”?

This script will run on Ubuntu 18.04 with OpenSSH client v7.6

Amandasaurus
  • 30,211
  • 62
  • 184
  • 246

1 Answers1

3

You can use ssh-keygen to check if the known_hosts file contains entries for a specific host, like this:

lacek@Teloth:~$ ssh-keygen -f ~/.ssh/known_hosts -F 192.168.153.254
# Host 192.168.153.254 found: line 18 
192.168.153.254 ssh-rsa AAAAB3Nza.....

You can use this to check the presence of a host key, and add it if it is not found, something like this:

#!/bin/bash

HOSTNAME=host.to.ssh.into
KNOWNHOSTS=~/.ssh/known_hosts

ssh-keygen -F $HOSTNAME -f $KNOWNHOSTS | grep -q found || ssh-keyscan $HOSTNAME >>$KNOWNHOSTS 2>/dev/null
Lacek
  • 6,585
  • 22
  • 28