Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
SSH known_hosts tools
# This is a short collection of tools that are useful for managing your
# known_hosts file. In this case, I'm using the '-f' flag to specify the
# global known_hosts file because I'll be adding many deploy users on this
# system. Simply omit the -f flag to operate on ~/.ssh/known_hosts
# Add entry for host
ssh-keyscan -H >> /etc/ssh/ssh_known_hosts
# Scan known hosts
ssh-keygen -f /etc/ssh/ssh_known_hosts -F
# Scan known hosts and grep (return code is 0 if matched; 1 if not matched)
ssh-keygen -f /etc/ssh/ssh_known_hosts -F | grep ''
# Count matches for host
ssh-keygen -f /etc/ssh/ssh_known_hosts -F | wc -l
# Remove entry for host
ssh-keygen -f /etc/ssh/ssh_known_hosts -R
rm /etc/ssh/ssh_known_hosts.old
# Wipe all known_hosts files
if [ -e ~/.ssh/known_hosts ]; then rm ~/.ssh/known_hosts; fi
if [ -e ~/.ssh/known_hosts ]; then rm ~/.ssh/known_hosts; fi
if [ -e ~/.ssh/known_hosts.old ]; then rm ~/.ssh/known_hosts.old; fi
if [ -e /etc/ssh/ssh_known_hosts ]; then rm /etc/ssh/ssh_known_hosts; fi
if [ -e /etc/ssh/ssh_known_hosts.old ]; then rm /etc/ssh/ssh_known_hosts.old; fi
# Show last return code; useful for testing the grep example
echo $?
Copy link

brettnak commented Mar 21, 2014

Not sure if this makes a difference for your use case but your first line, in addition to adding an entry, will erase all other system entries. For newer readers, it might be a good idea to change it to an append redirect, >>, and avoid accidentally erasing other known entries.

Copy link

foxx commented Aug 30, 2015

Super useful, thanks for sharing!

Copy link

jeffryang24 commented Jul 28, 2018

On line 13, if you use -H parameter, the grep will always return 1 because the value of has been hashed. You must remove the -H to achieve zero exit code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment