Fast SSH Key Reset

I’m frequently swapping Raspberry Pi boards and re-flashing SD cards, and constantly facing the issue when SSH suddenly refuses to connect because the host key changed. Not a big deal, just annoying when all you want is to tinker.

SSH stores fingerprints in known_hosts. Reusing the same IP or hostname with a different system confuses it, and SSH assumes something sketchy is happening.

The usual fix is editing ~/.ssh/known_hosts and deleting the old entry. Works fine, but gets tedious, because you will have to find this particular host in the list of and remove all its appearances.

Let’s make this a little bit easier and automate this process.

  1. Open ~/.bashrc (or ~/.zshrc, whichever applies) and add this function at the bottom:
function ssh-reset() {
    local host=$1
    local ip_address=$(echo $host | awk -F'@' '{print $2}')
    ssh-keygen -R "$ip_address"
    ssh "$host"
}

2. Reload

> source ~/.bashrc

or

> source ~/.zshrc

3. Use:

> ssh-reset pI@192.168.1.100

That’s it. All it does is looks up the ip address in the list of known hosts deletes it and proceeds with the ssh command as if it was ran for the first time.

PS

Sure, you can always use the good old:

> ssh-reset pI@192.168.1.100

However, to do it, you’ll first have to try ssh’ing to the host, potentially get the WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!, and then do the ssh-reset. Creating a custom function saves the trip into the known_hosts.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *