Saturday, April 6, 2013

Function for removing keys from known_hosts

When connecting via ssh to a remote host you are asked to confirm the key fingerprint. This is added to ~/.ssh/known_hosts file so no further confirmation is required.
What about when the remote key has changed? You need to delete the key from this file.
I've written a small function to make this deleting easier, just by typing one command:

sshrm-key <nr>

Here's the function to use it on your system, place it in .bashrc:
sshrm-key() {
    if ! [[ "$1" =~ ^[0-9]+$ ]] ; then
        echo "Function for removing Nth key from known_hosts file"
        echo "USAGE: sshrm-key <line number>";
    elif [ $1 -gt $(grep -c "" ~/.ssh/known_hosts) ]; then
        echo No such line...
    else
        echo -n "Deleting host key: "
        awk -v linenr=$1 'NR==linenr {print $1}' ~/.ssh/known_hosts | grep '[^ ]' --color
        sed -i ''$1'd' ~/.ssh/known_hosts
    fi
}

3 comments:

  1. ssh-keygen -R host with backup known_hosts :)

    ReplyDelete
  2. that is too long and unconfortable to type. I rather type sshr and number, it's faster ;)

    ReplyDelete