SSH - known_host file

By kimot, 27 December, 2022

The ssh known_hosts file is a file that stores the public key of all of the servers that you have connected using ssh.

In OpenSSH, the collection of known host keys is stored in /etc/ssh/known_hosts and in .ssh/known_hosts in each user’s home directory.

When connecting to a host for the first time, ssh usually adds the remote host’s public key to the user’s known_hosts file.

These keys are used to verify the identity of the remote host, thus protecting against impersonation or man-in-the-middle attacks.

When a key is removed, it will then be appended to the file ~/.ssh/known_hosts.old in case it is needed later.

 

Example :

ibmserver,10.150.5.50 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPMOR6kbKvCm96tmFGA3LKG89YwM72aQ6d5lVX6ucBvdL35T/auzSZPmf8heMLlVPtkNlx3rIZONx9MEUcK5J5U=

 

To view known hosts :

cat ~/.ssh/known_hosts

To add new host :

ssh-keyscan -t rsa [remote.server.com] >> ~/.ssh/known_hosts

To remove host from file :

ssh-keygen -R [remote.server.com]

To show public keys for remote server (only for port 22 in this example):

ssh-keyscan -p 22 10.50.5.130

-p only specified port
-t only specified type (dsa / ecdsa / ed25519 / ecdsa-sk / ed25519-sk / rsa)

 

To update the known_hosts file with the fingerprint of the particular hostname or the IP address :

ssh-keyscan -H 10.50.5.130 >> ~/.ssh/known_hosts