Created
July 22, 2016 18:57
-
-
Save cfg/b4cb26902367177c4bb2fbcf52d762a0 to your computer and use it in GitHub Desktop.
Attempt to locate the SSH public and private key used for a host/user@host.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
HOST="$1" | |
[[ -z "$HOST" ]] && (>&2 echo "Usage: $0 [user@]hostname") && exit 1 | |
OUT="$(ssh -o ConnectionAttempts=1 -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o "PreferredAuthentications=publickey" -T "$HOST" -v true 2>&1 | grep -B3 "Authentication succeeded (publickey)" )" | |
RET="$?" | |
if [[ "$RET" -ne "0" ]] ; then | |
(>&2 echo "ERROR (errno: $RET): Unable to connect or authenticate to $HOST") | |
exit 1 | |
fi | |
PRIVKEY="$(echo "$OUT" | perl -ne 'if ( /^[^:]+: Offering \w+ public key: (.*)$/ ) { print $1 }')" | |
RET="$?" | |
if [[ "$RET" -ne "0" ]] ; then | |
(>&2 echo "ERROR: Unable to find a matching SSH key $HOST") | |
exit 1 | |
else | |
PRIVKEY="${PRIVKEY/%[$'\t\r\n']*}" ; # remove trailing tab, newline, carriage return | |
PUBKEY="${PRIVKEY}.pub" | |
echo "PRIVKEY: $PRIVKEY" | |
[[ -f "$PUBKEY" ]] && echo "PUBKEY: $PUBKEY" || echo "Pubkey $PUBKEY was not found" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment