-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean_ssh_known_hosts.sh
executable file
·68 lines (62 loc) · 1.73 KB
/
clean_ssh_known_hosts.sh
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/bin/bash
hostFile=~/.ssh/known_hosts
removeBad=0
verbose=0
usage="
$0 [-f <hostfile>] [-r] [-v]
This will find mismatching ssh known_hosts keys and remove them.
-f <hostfile> - file to scan and modify if using -r
-r - remove mismatching host keys from file
-d - remove hosts that you cannot connect to from file
-v - verbose, includes printing OK host keys
"
while getopts 'f:rdvh' opt; do
case $opt in
f)
hostFile=$OPTARG
;;
r)
removeBad=1
;;
d)
removeConnect=1
;;
v)
verbose=1
;;
h)
echo "$usage"
exit
;;
esac
done
shift $((OPTIND-1))
for host in `ssh-keygen -l -f $hostFile | cut -d' ' -f3 | cut -d, -f1 | grep -v '^\W'`; do
echo Checking $host
# check simple ssh connection
ssh $host -o 'StrictHostKeyChecking=yes' -o 'PasswordAuthentication=no' \\exit 2>&-
if [[ $? != 0 ]]; then
# well that didn't work, now check if can connect but just get denied access (key problems or connection problems)
ssh $host -o 'StrictHostKeyChecking=yes' -o 'PasswordAuthentication=no' -o 'ConnectTimeout=5' \\exit 2>&1 | grep -e 'Permission denied' -e 'timed out' 1>&-
if [[ $? == 0 ]]; then
# skip if connection problems and did not use -d option
if [[ $removeConnect == 1 ]]; then
echo $host : Could not connect with ssh key
else
echo $host : Could not connect with ssh key. skipping.
continue
fi
fi
# remove hostkey if -r option was used
if [[ $removeBad == 1 ]]; then
ssh-keygen -R $host -f $hostFile 1>&-
echo $host : removed host key from $hostFile
else
echo $host : host key mismatch found in $hostFile
fi
# bark with -v
elif [[ $verbose == 1 ]]; then
echo $host : host key matches OK
fi
done
# Niko The Dread Pirate (@deathanchor)