Removing entries from ~/.ssh/known_hosts

2012-12-10 10:51 PST

My work requires that I ssh in and out of several hundred virtual machines every month These machines are constantly being torn down, with new machines replacing them in potentially the same address space. That churn means I see messages like this every week:

[username:~] $ ssh username@localhost
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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
4d:1f:b4:5d:67:40:61:94:7e:62:3f:d4:8b:d9:b7:6d.
Please contact your system administrator.
Add correct host key in /Users/username/.ssh/known_hosts to get rid of this message.
Offending RSA key in /Users/username/.ssh/known_hosts:185
RSA host key for localhost has changed and you have requested strict checking.
Host key verification failed.
[username:~] $

Because of my environment, and the nature of these machines, I do not need to be concerned about a man-in-the-middle attack, and can with great confidence be sure that the machine in question has been replaced and that the RSA key of the machine in question does indeed need to be updated. To do that I used to delete the appropriate line (185 in this case) from ~/.ssh/known_hosts and be on my way. But a few months ago, I learned that ssh-keygen has a facility to do just this.

ssh-keygen -R <hostname> will remove the offending line from the known_hosts file. so in this case all I have to do is issue ssh-keygen -R localhost and the line in question is removed, and then I can go about connecting again: ssh username@localhost.

Not only is this the “right” way to manage the entries in this file, but now I don’t risk accidentally munging a different hosts’s key in my known_hosts file.