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
You can use
ssh-keygen
to check if theknown_hosts
file contains entries for a specific host, like this:You can use this to check the presence of a host key, and add it if it is not found, something like this: