Skip to content

Instantly share code, notes, and snippets.

@rodneyshupe
Created November 3, 2019 21:11
Show Gist options
  • Save rodneyshupe/22c08fd060a383d837e1476400180792 to your computer and use it in GitHub Desktop.
Save rodneyshupe/22c08fd060a383d837e1476400180792 to your computer and use it in GitHub Desktop.
Bash function to create a SSH key and upload to Lastpass using the Lastpass CLI.
# Usage: create-sshkey KEYNAME PASSPHRASE [COMMENT]
# KEYNAME = The file name used for the key.
# PASSPHRASE = The pass phrase to be used. If you wish to not use a passphrase just use a blank string (i.e. "")
# COMMENT = Optional Comment. If skipped the KEYNAME will be used.
#
# Example: create-sshkey my_secret.key "This is my secret passphrase" "An example key."
function create-sshkey() {
KEYNAME=$1
PASSPHRASE=$2
COMMENT=${3:-$KEYNAME}
KEYGEN_CMD="ssh-keygen -t rsa -b 4096 -N \"${PASSPHRASE}\" -f ~/.ssh/${KEYNAME} -C '${COMMENT}' > ~/.ssh/${KEYNAME}.txt"
eval "$KEYGEN_CMD"
if [ -f ~/.ssh/${KEYNAME} ] && [ -f ~/.ssh/${KEYNAME}.pub ] && [ -f ~/.ssh/${KEYNAME}.txt ]; then
if [ -x "$(command -v lpass)" ]; then
if [ $(lpass status --quiet && echo 0 || echo 1) -eq 1 ]; then
echo
read -r -p "This script requires Lastpass access. Please enter your Lastpass username " response
if [ -n $response ]; then
lpass login $response
fi
fi
fi
if [ -x "$(command -v lpass)" ] && [ $(lpass status --quiet && echo 0 || echo 1) -eq 0 ]; then
echo -en "Date: $(date +%B,%d,%Y)\nPrivate Key: $(cat ~/.ssh/${KEYNAME})\nPublic Key: $(cat ~/.ssh/${KEYNAME}.pub)\nPassphrase: ${PASSPHRASE}\nFormat: rsa\nBit Strength: 4096\nNoteType: SSH Key\nNotes: ${KEYGEN_CMD}\n\n$(cat ~/.ssh/${KEYNAME}.txt)\n" | lpass add --sync=now --non-interactive --note-type=ssh-key "ssh keys/${KEYNAME}"
rm ~/.ssh/${KEYNAME}.txt
else
echo "Unable to upload key to Lastpass. Skipping."
cat ~/.ssh/${KEYNAME}.txt
fi
else
echo "Problem generating key!"
echo " Keyname: $KEYNAME"
echo " Passphrase: $PASSPHRASE"
echo " Comment: $COMMENT"
echo " Command: $KEYGEN_CMD"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment