What is the good practice for adding known keys/fingerprints to known_hosts

There are plenty of answers to questions similar to this one but I can't seem to find one with a clear answer. They all either grab the public key at least once, ignore the key altogether, or write directly to the known_hosts file (implies no hash)

I have the server's fingerprint and/or public key. I would like a shell command to add it to the client's known_hosts file. This has to use whatever is configured (hash/no-hash)

Also, the script will do a git pull from this server so I don't know if providing port information at this point is relevant or not. Please tell me if it is.

Thanks. And feel free to point me in the right direction if this has already been answered and I missed it somehow.

PS - Extra info: One of the reasons I ask about ports is because I've done the following to no success (I'm aware this is getting the key from the host which I would rather not do):

ssh-keygen -R my.awesome.host # hostname
ssh-keygen -R 1.2.3.4         # IP
ssh-keygen -R my.awesome.host,1.2.3.4
ssh-keyscan -H my.awesome.host,1.2.3.4 >> ~/.ssh/known_hosts
ssh-keyscan -H 1.2.3.4 >> ~/.ssh/known_hosts
ssh-keyscan -H my.awesome.host >> ~/.ssh/known_hosts

But when I git clone (via ssh) I'm met with a resounding:

The authenticity of host '[my.awesome.host]:7999 ([1.2.3.4]:7999)' can't be established.
RSA key fingerprint is fi:ger:pr:in:ti:nf:or:ma:ti:on
Are you sure you want to continue connecting (yes/no)?

Yet ssh [email protected] does not prompt me about the fingerprint.


Having a public key, you can simply write the key into the known_hosts file and possibly re-hash, if you need to:

HOSTNAME=my.awesome.host
PORT=7999
PUBKEY="ssh-rsa AAAAB3NzaC1yc2EAAAAD...E"
KNOWN_HOSTS="~/.ssh/known_hosts"
echo "[$HOSTNAME]:$PORT $PUBKEY" >> $KNOWN_HOSTS
# re-hash, if needed:
ssh -G -p $PORT $HOSTNAME | grep "hashknownhosts yes" && \
  ssh-keygen -H -f $KNOWN_HOSTS

The -G switch for ssh is fairly new. If it does not work, you will have to determine whether to hash the known hosts or not in different way (or do it regardless the conditions).

Hashing file with already hashed hosts does not touche these lines.

I didn't try the above script, but you should be able to get the point from that (and fix typos, if there are some).