How to manage my .ssh/known_hosts file

To find out which entry is for a known hostname in known_hosts:

 # ssh-keygen -H  -F <hostname or IP address>

To delete a single entry from known_hosts:

 # ssh-keygen -R <hostname or IP address>

With difficulty...

Ubuntu by default hashes hostnames the known_hosts file (this is not the default openssh behaviour), to make it difficult for anyone reading the file to know what systems you access.

If you really wanted to clean out the file, simplest option is probably just delete it and check the keys for servers you know as they arise, but really I'd just leave known_hosts alone.

You can stop new hosts entries from being hashed by commenting out the option in /etc/ssh/ssh_config

#HashKnownHosts yes

If you've got a list of all your hosts, you can do something like

ssh-keyscan -t rsa,dsa -f list_of_hosts > ~/.ssh/known_hosts

That will overwrite your .ssh/known_hosts file with a newly generated one based on scanning the hosts.

And also do what theotherreceive suggests; HashKnownHosts is more annoyance than help here.


I had over 300 stale old entries in my known_hosts file. Not sure that it will work for all systems (or even most systems) but here is my Q&D script. You may have to adjust the matching strings or location.

#!/bin/sh
list=`cat ~/.ssh/known_hosts | awk '{print $1}' |sed -e 's/,/ /g' | sort -u `

listsorted=$(printf "%s\n" ${list[@]} | sort -u)
echo $listsorted
#listsorted="10.2.10.1"
echo > /tmp/sshstat.txt
for host in $listsorted ;
do
echo $host 
ssh -oBatchMode=yes -oConnectTimeout=2  root@${host} "exit" >/tmp/sshstat.txt 2>&1 
ret=$?
if [ $ret -ne 0 ]; then
     echo "Failed: $host"
     echo sed -i.bak \"/$host/d\" "~/.ssh/known_hosts" | sh
else
    grep "Offending RSA" /tmp/sshstat.txt |  sed -e 's/:/ /g' | awk '{printf "sed -i.bak -e \"%dd\" %s  \n", $6, "~/.ssh/known_hosts" }' | sh
   fi
done
#echo $list