Skip to content

Instantly share code, notes, and snippets.

@cfg
Created July 22, 2016 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfg/b4cb26902367177c4bb2fbcf52d762a0 to your computer and use it in GitHub Desktop.
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.
#!/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