Removal of Host-Key from ~/.ssh/known_hosts

Occasionally, a host key is changed on a host, either manually or possibly automatically through an update of OpenSSH. When you log in via ssh to the host in question you will get the following message:

$ ssh aix01
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:xYglDF3cuHCCrxtbFUbpofpmhNs9MiO114vAT4qVX2M.
Please contact your system administrator.
Add correct host key in /home/as/.ssh/known_hosts to get rid of this message.
Offending RSA key in /home/as/.ssh/known_hosts:2
RSA host key for aix01 has changed and you have requested strict checking.
Host key verification failed.
$

Now many administrators use vi (or another editor) to remove the entry with the old host key from the known_hosts file. The line number of the corresponding entry is given in the output above, /home/as/.ssh/known_hosts:2 means the entry is in line 2 of the file.

It is much easier to remove the obsolete host key using the ssh-keygen command and the “-R” (remove) option:

$ ssh-keygen -R aix01
# Host aix01 found: line 2
/home/as/.ssh/known_hosts updated.
Original contents retained as /home/as/.ssh/known_hosts.old
$ 

The command creates a copy of the file, with the extension “.old” and removes the desired entry. This is much easier than using an editor!

If you want to know if a host key for a system already exists in the known_hosts, there is the option “-F” (find) for this purpose:

$ ssh-keygen -F aix02
# Host aix02 found: line 49 
aix02,192.168.178.49 ssh-rsa AAAAB3NzaC1yc2E...
$

The public host key and the line for the system are shown.

%d bloggers like this: