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 :

IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
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
54:9d:c0:37:3a:80:48:6c:82:ec:d1:84:93:61:24.
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”]
#!/bin/bash
H=$1

[[ -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.

Join the Conversation

5 Comments

  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. This way should work..

    #!/bin/bash
    H=$1

    [[ -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 comment

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.