Skip to content

Instantly share code, notes, and snippets.

@Frick
Last active April 9, 2019 14:48
Show Gist options
  • Save Frick/9bdf130d3021dcfbbfa5 to your computer and use it in GitHub Desktop.
Save Frick/9bdf130d3021dcfbbfa5 to your computer and use it in GitHub Desktop.
Quick way of fixing host SSH changes without flat out disabling StrictHostKeyChecking
function fixssh {
local hostname=""
local ip=""
for arg in $@; do
local hostout=$(host "$arg" 2>/dev/null)
if [ $? -eq 0 ]; then
local out=$(echo "$hostout" | grep -o "has address .*$" | grep -Eo "[0-9.]{7,15}")
if [ $? -eq 0 ]; then
local hostname="$arg"
local ip="$out"
else
local out=$(echo "$hostout" | grep -o "domain name pointer .*\." | cut -d' ' -f4)
if [ "$out" != "" ]; then
local hostname="${out:0:-1}"
local ip="$arg"
fi
fi
break
fi
done
if [ "$ip" != "" ]; then
ssh-keygen -f ~/.ssh/known_hosts -R "$ip"
ssh-keyscan -H "$ip" 2>/dev/null >> ~/.ssh/known_hosts
fi
if [ "$hostname" != "" ]; then
ssh-keygen -f ~/.ssh/known_hosts -R "$hostname"
ssh-keyscan -H "$hostname" 2>/dev/null >> ~/.ssh/known_hosts
fi
ssh $@
}

Examples:

When I try to SSH somewhere and get the big, scary MITM warning and know about / expected the change, I simply have to hit ⬆️ , Ctrl+a, and type fix then hit ↩️ and I'll be on the machine in a moment.

$ ssh somemachine
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
5a:59:e0:fe:60:f4:c6:01:c3:9e:0a:58:d2:72:c1:0f.
Please contact your system administrator.
Add correct host key in /home/frick/.ssh/known_hosts to get rid of this message.
Offending RSA key in /home/frick/.ssh/known_hosts:411
  remove with: ssh-keygen -f "/home/frick/.ssh/known_hosts" -R somemachine
RSA host key for somemachine has changed and you have requested strict checking.
Host key verification failed.
frick@frick:~$ fixssh somemachine
# Host 10.144.144.44 found: line 69 type RSA
/home/frick/.ssh/known_hosts updated.
Original contents retained as /home/frick/.ssh/known_hosts.old
# Host somemachine found: line 410 type RSA
/home/frick/.ssh/known_hosts updated.
Original contents retained as /home/frick/.ssh/known_hosts.old

[frick@somemachine ~]$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment