Shell Script To Remove All Keys Belonging To Hostname From a ~/.known_hosts File

in Categories File-management last updated December 14, 2009
#!/bin/bash
# A simple shell script to clean (delete)  ~/.known_hosts file hostname entry.
# This is useful when remote server reinstalled or ssh keys are changed!
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
host="$1"
 
[[ $# -eq 0 ]] && { echo "Usage: $0 host.name.com"; exit 1;}
 
ips=$(host "$host" | awk -F'address' '{ print $2}' | sed -e 's/^ //g')
ssh-keygen -R "$host"
for i in $ips
do
	ssh-keygen -R "$i"
done

How Do I Use This Script?

Simply run it as follows:
./script.sh www-03.nixcraft.net.in


Share this on:

1 comment

  1. ips=$(host “$host” | awk -F’address’ ‘{ print $2}’ | sed -e ‘s/^ //g’)

    could be shorten to: ips=$(host “$host” | awk ‘/address/ { print $NF }’)

    Have a question? Post it on our forum!