Automate SSH known_hosts cleanup

If you like me, you have to do a lot of installs[1] of the same test machine with the same IP and have to ssh it you will notice this annoying message :

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
Please contact your system administrator.
Add correct host key in /home/cboudjnah/.ssh/known_hosts
to get rid of this message.
Offending key in /home/cboudjnah/.ssh/known_hosts:595
Password authentication is disabled to avoid
 man-in-the-middle attacks.
Keyboard-interactive authentication is disabled to avoid
man-in-the-middle attacks.
Agent forwarding is disabled to avoid man-in-the-middle attacks.

I have automated the cleanup by a script :
[code lang=”bash”]

[[ -z ${H} ]] && { echo “Need a host as argument”; exit 1 ;}
LINE=$(ssh -o StrictHostKeyChecking=yes $1 ‘exit’ 2>&1 | sed -n ‘/Offending key/ { s/.*://;s/r//;p }’)
[[ -z ${LINE} ]] && { echo “Nothing to clean”; exit; }
sed -i -n “$LINE!p” ~/.ssh/known_hosts[/code]
[1] Like having to tests bunch of FAI.

5 thoughts on “Automate SSH known_hosts cleanup”

  1. I had problems with line 7 of the script. the exclamation point “!” was causing problems in bash. I was getting the error :

    ‘ed: -e expression #1, char 3: Unknown command: `

    I attempted to escape the exclamation point which I was able to do on the command line but not in a bash script. On the command line I surrounded the “!” in single quotes and the syntax became :

    sed -i -n “$LINE”‘!p’ ~/.ssh/known_hosts

    The only way I could get it to work in a bash script was to assemble the sed code in a file and call that file :

    instead of :

    sed -i -n “$LINE!p” ~/.ssh/known_hosts

    I used :

    echo -n “$LINE” | tr -d ‘\r’ > test-known_hosts.sed
    echo ‘!p’ >> test-known_hosts.sed
    sed -i -n -f test-known_hosts.sed ~/.ssh/known_hosts

    which worked

  2. mmmm beats my manual way of reading the line out of the error then running:
    sed -i ‘303 d’ /home/dobbo/.ssh/known_hosts

  3. This way should work..


    [[ -z ${H} ]] &LINE=$(ssh -o StrictHostKeyChecking=yes $1 'exit' 2>&1 | sed -n '/Offending key/ { s/.*://;s/\r//;p }')
    [[ -z ${LINE} ]] &sed -i -n "$LINE!p" ~/.ssh/known_hosts

    you should strip a “\r” (carriage return) and not a literal “r” 😉

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.