This little script takes an IP or hostname as a parameter, and if there is an offending key in the .ssh/known_hosts it removes it and replaces it with the current valid one useful if you are moving/reinstalling a large amount of servers …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/bin/bash #=============================================================================== # FILE: ssh-cleankey.sh # USAGE: ./ssh-cleankey.sh # # DESCRIPTION: deletes stale ssh known_hosts entries #=============================================================================== # true or fasle VERBOSE=false #=== Exit codes ================================================================ # 1 - Not a valid IP or not reachable #=============================================================================== #=== FUNCTION ================================================================ # NAME: print_help # DESCRIPTION: Prints help and exits #=============================================================================== print_help() { #{{{ echo "Usage: `basename $0` " echo "" echo "e.g. ./`basename $0` 1.2.3.4" echo "" exit 0 } #}}} if [[ $# -eq 1 ]] then HOST="${1}" else print_help fi ping -w1 -c1 $HOST >/dev/null 2>&1 if [[ $? != 0 ]] then $VERBOSE && echo "ERROR: $HOST is either not a valid IP/hostname, or is not reachable via ping" exit 1 fi Check=$(ssh -o connecttimeout=10 -o stricthostkeychecking=no $HOST true 2>&1|grep -c "Offending key") if [[ $Check -gt 0 ]] then $VERBOSE && echo "$HOST is stale, updating known_hosts" ssh-keygen -R $HOST >/dev/null 2>&1 ssh -o connecttimeout=10 -o stricthostkeychecking=no $HOST true >/dev/null 2>&1 else $VERBOSE && echo "$HOST is OK" fi exit 0 |