Skip to content

Instantly share code, notes, and snippets.

@KangOl
Created December 28, 2012 18:43
Show Gist options
  • Save KangOl/4400699 to your computer and use it in GitHub Desktop.
Save KangOl/4400699 to your computer and use it in GitHub Desktop.
Script that return the name of the current ssh user
#!/usr/bin/env bash
if [ -z "$SSH_TTY" ]; then
exit 3
fi
LOGINTIME=`last -RF ${SSH_TTY:5} | head -n1 | awk '{print $6}'`
MATCH=`echo $USER $SSH_CLIENT | awk '{print " Accepted publickey for " $1 " from " $2 " port " $3 " ssh2"}'`
FINGERPRINT=`grep $LOGINTIME /var/log/auth.log | grep -v " debug1: " | grep -B1 "$MATCH" | head -n1 | awk '{print $NF}'`
if [ -z "$FINGERPRINT" ]; then
exit 2;
fi
KEYS=/tmp/keys.$$
KF=/tmp/sshkey.$$
cat ~/.ssh/authorized_keys ~/.ssh/authorized_keys2 > $KEYS 2>/dev/null
while read -r line; do
echo $line > $KF
F=`ssh-keygen -l -f $KF | awk '{print $2}'`
rm -f $KF
if [ "$FINGERPRINT" = "$F" ]; then
rm -f $KEYS
U=`echo $line | awk '{print $NF}'`
echo $U
exit 0
fi
done < $KEYS
rm -f $KEYS
exit 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment