Search this site


Metadata

Articles

Projects

Presentations

Hack for quickly trimming invalid ssh keys

If you reimage a machine or change dns, you may get any of these messages when sshing in:
Offending key for IP in /home/jsissel/.ssh/known_hosts:239
Matching host key in /home/jsissel/.ssh/known_hosts:252
Offending key in /home/jsissel/.ssh/known_hosts:237
Seem familiar? Here's a very quick way to trim those.
#!/bin/sh

eval "value=\$$#"

if [ "$#" -lt 1 ] ; then
  echo "Invalid arguments."
  exit 1
fi

if ! echo "$value" | egrep -q '.*:[0-9]+$' ; then
  echo "Invalid file:lineno format: $value"
  exit 1
fi

echo "$value" | awk -F: '{print "sed -i -e "$2"d",$1}' | sh -x
  • Put this in ~/bin/clearssh.sh
  • chmod 755 ~/bin/clearssh.sh
  • ln -s ~/bin/clearssh.sh ~/bin/Matching
  • ln -s ~/bin/clearssh.sh ~/bin/Offending
Now the next time you see these messages and want to clear the offending key, just paste the log message, as a command, into your terminal:
jls(~) % Offending key for IP in /home/jsissel/.ssh/known_hosts:239
+ sed -i -e 239d /home/jsissel/.ssh/known_hosts
Makes for a quick fix if you hit these messages in your normal day.

I prefer this to using 'ssh-keygen -R' as the error message has exactly the information you need to clear the bad key.