Skip to content

Instantly share code, notes, and snippets.

@postazure
Last active November 9, 2017 17:01
Show Gist options
  • Save postazure/142181db1e2acb676407790c5dac1b63 to your computer and use it in GitHub Desktop.
Save postazure/142181db1e2acb676407790c5dac1b63 to your computer and use it in GitHub Desktop.
Copy ssh key from lastpass to a machine for a short amount of time
#!/usr/bin/env bash
# This script temporarily adds an ssh key until the end of the working day, from Lastpass.
# Requires the lastpass cli, if you don't have it, install with `brew install lastpass-cli --with-pinentry`
# Store rsa_id in a note in lastpass called 'rsa_id' in a folder called 'Github'.
#
# Usage:
# add_key [hours]
#
# hours Specifies the number of hours to add the ssh key. Overrides the default end of day behavior.
#
# Configure these values with your key and desired end of day
#
END_OF_DAY=18
#
# End config
#
KEY_FILE=/tmp/key-from-lp
cleanup () {
echo "Cleaning up temp file"
# ignore stderr from rm incase the hook is called twice
rm -f $KEY_FILE &> /dev/null
exit 0
}
trap cleanup EXIT ERR INT TERM
LPASS_EMAIL=$1
HOURS=$2
MINUTES=0
if [ -z $HOURS ]; then
CURRENT_HOUR=$(date +'%H')
CURRENT_MINUTE=$(date +'%M')
if [ $CURRENT_HOUR -ge $END_OF_DAY ]; then
echo ""
echo "You are running this after the end of the day. Please specifiy hours."
echo " usage: $0 <hours>"
echo ""
exit 1
fi
HOURS=$(expr $END_OF_DAY - $CURRENT_HOUR - 1)
MINUTES=$(expr 60 - $CURRENT_MINUTE)
if [ "$MINUTES" == "60" ]; then
MINUTES=0
fi
echo ""
echo "Current time is $CURRENT_HOUR:$CURRENT_MINUTE"
echo " Setting expiration for $HOURS:$MINUTES to expire at ${END_OF_DAY}:00"
echo ""
else
echo ""
echo "Setting expiration for $HOURS hours"
echo ""
fi
lpass login $LPASS_EMAIL
/usr/bin/ssh-add -D
lpass show Github/rsa_id --notes > $KEY_FILE
chmod 0600 $KEY_FILE
/usr/bin/ssh-add -t ${HOURS}H${MINUTES}M $KEY_FILE
lpass logout -f
# Temp file is cleaned up by cleanup() function which traps exit interrupts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment