Skip to content

Instantly share code, notes, and snippets.

@CarsonF
Created April 20, 2016 17:37
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 CarsonF/dda63e9e349ce733689e221fb94dd3a5 to your computer and use it in GitHub Desktop.
Save CarsonF/dda63e9e349ce733689e221fb94dd3a5 to your computer and use it in GitHub Desktop.
Lists SSH public key fingerprints
#!/usr/bin/env bash
# Lists SSH public key fingerprints
file=$1
hash=""
if [[ "$OSTYPE" == "darwin"* ]]; then
hash="-E MD5"
fi
if [[ " $@ " == *" -h " ]] || [[ " $@ " == *" --help " ]]; then
cat << EOF
Lists SSH public key fingerprints
Usage:
$0 [-h|--help] [<username>]
$0 <file>
$0 <directory>
Print fingerprints for user bob's authorized_keys
$0 bob
Print fingerprints for public keys in file given
$0 .ssh/authorized_keys
Print fingerprints for public keys in directory given (recursive)
$0 .ssh
Print fingerprint for public key given
$0 key.pub
EOF
exit 2
fi
if [ ! -z "$file" ] && [ -d ${file} ]; then
noRunIfEmpty="-r"
if [[ "$OSTYPE" == "darwin"* ]]; then
noRunIfEmpty=""
fi
find ${file%/} -type f -name *.pub | xargs ${noRunIfEmpty} -n 1 sh -c "echo \$0; ssh-keygen -l $hash -f \$0; echo"
exit 0
fi
if [ -f "$file" ] && [[ ${file} != *"authorized_keys" ]]; then
ssh-keygen -l ${hash} -f ${file}
exit 0
fi
if [ ! -f "$file" ]; then
if [ -z "$file" ]; then
file=${USER}
fi
if [[ "$OSTYPE" == "darwin"* ]]; then
users=$(dscl . -list /Users)
else
users=$(cut -d: -f1 /etc/passwd)
fi
if [[ ${users} == *${file}* ]]; then
userAuthKeys=$(eval echo ~${file}/.ssh/authorized_keys)
if [ -f "$userAuthKeys" ]; then
echo "Fingerprints of authorized keys for ${file}:"
file=${userAuthKeys}
else
echo "Could not read file: $file or $userAuthKeys"
exit 1
fi
else
echo "Could not read file: $file"
exit 1
fi
fi
if [[ "$OSTYPE" == "darwin"* ]]; then
# OS X use a temp file since STDIN doesn't work
temp=$(mktemp -q -t "$0.XXXXXXXXXX")
tempEscaped=$(echo $temp | sed -e 's/[\/&]/\\&/g')
fileEscaped=$(echo $file | sed -e 's/[\/&]/\\&/g')
while read l; do
if [[ -n ${l} && ${l###} = ${l} ]]; then
echo "$l" >| "$temp"
# Replace temp file path in stderr to input file
ssh-keygen -l ${hash} -f ${temp} 3>&1 1>&2 2>&3 3>&- | sed "s/$tempEscaped/$fileEscaped/"
# If ssh-keygen failed, file is probably not an authorized_keys file so exit
if [ $PIPESTATUS -ne 0 ]; then
rm -f "$temp"
exit 1
fi
>| "$temp"
fi
done < ${file}
rm -f "$temp"
else
while read l; do
if [[ -n ${l} && ${l###} = ${l} ]]; then
ssh-keygen -l $hash -f /dev/stdin <<<$l
fi
done < ${file}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment