Skip to content

Instantly share code, notes, and snippets.

@kfox
Created February 8, 2013 15:45
Show Gist options
  • Save kfox/4739828 to your computer and use it in GitHub Desktop.
Save kfox/4739828 to your computer and use it in GitHub Desktop.
An easy way to remove old SSH host keys from your ~/.ssh/known_hosts file. Useful if you often re-image systems.
# forget.sh: remove matching lines from ~/.ssh/known_hosts
# usage: forget <hostname|IP|substring> [...]
function forget {
known_hosts=~/.ssh/known_hosts
for host in $*
do
host=$(echo "${host}" | sed -e 's/^ssh:\/\///' -e 's/^.*@//')
line=$(awk '{ print $1 }' ${known_hosts} | grep -n "${host}" | sed 's/:.*$//g' | xargs)
while [ -n "${line}" ]
do
l=$(echo $line | awk '{ print $1 }')
echo -n "==> removing from ${known_hosts}: "
awk '{ if (NR==n) print $1 }' n=$l ${known_hosts}
sed -i '.old' "${l}d" ${known_hosts}
line=$(awk '{ print $1 }' ${known_hosts} | grep -n "${host}" | sed 's/:.*$//g' | xargs)
done
done
}
@kfox
Copy link
Author

kfox commented Feb 8, 2013

I just include this in my ~/.bashrc.

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