DEV Community

Tobias Grasse
Tobias Grasse

Posted on

Quickly remove an entry from known_hosts

Do you SSH to servers a lot? Then this will sooner or later pop up:

Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
<host key>.
Please contact your system administrator.
Add correct host key in /path/to/.ssh/known_hosts to get rid of this message.
Offending key in /path/to/.ssh/known_hosts:<line>
RSA host key for [ip-or-host]:<port> has changed and you have requested strict checking.
Host key verification failed.
Enter fullscreen mode Exit fullscreen mode

This is one of the user-friendlier error messages I've encountered: What went wrong, possible causes, what to do, pointer to the known_hosts file/line that caused this.

When you connect to an existing, well-known server that wasn't modified, you should check with your friendly admin or hosting provider – in case someone has actually meddled with your server.

However, my work on IoT devices involves a lot of SSH'ing to local devices, and frequent teardown/re-flash means they get assigned the same IP address/host name as a previous device – but with a different host key. So each time, OpenSSH will issue its dutiful warning above. I don't want to disable strict checking completely or on a per-host basis. Removing the offending line by hand each time gets tedious, but luckily OpenSSL's ssh-keygen can take care of this:

ssh-keygen -R <ip-or-hostname> -f "/path/to/.ssh/known_hosts"
Enter fullscreen mode Exit fullscreen mode

Still to much to type on a regular basis. My shell of choice is fish, so I wrapped this in a function rmkh (“remove known host”):

function rmkh -d "removes a given host from ~/.ssh/known_hosts"
  ssh-keygen -R "$argv" -f "/path/to/.ssh/known_hosts"
Enter fullscreen mode Exit fullscreen mode

So the next time I get a host verification message, I can just run rmkh <offending-host-or-ip> and get on with it. Also works with multiple hosts.

Note: At least inside a fish function, this needs to have the full path to your known_hosts file as a string, so don't use a tilde and quote everything to be safe.

Top comments (0)