Skip to content

Instantly share code, notes, and snippets.

@fabricat
Last active September 25, 2020 09:18
Show Gist options
  • Save fabricat/792c529960f25ccfd36ec670e7779f8f to your computer and use it in GitHub Desktop.
Save fabricat/792c529960f25ccfd36ec670e7779f8f to your computer and use it in GitHub Desktop.
Load a private key in ssh-agent (from file or Lastpass), eventually using also Pageant (on Cygwin)
#!/bin/bash
### Setup: source this script from your .bashrc or .bash_profile
### In Cygwin, you can use Putty (Plink + Pageant) for GIT - see https://git-scm.com/docs/git
export GIT_SSH_COMMAND='"/cygdrive/c/Program Files/PuTTY/plink.exe" -agent'
export GIT_SSH_VARIANT='plink'
### Some tools don't like Putty (e.g. Ansible): then use also "ssh-agent"
environ="$HOME/.ssh/environment"
if [ -f "$environ" ]; then
. "$environ" >/dev/null
fi
if [ -z "$SSH_AUTH_SOCK" ] || ! ps -p "$SSH_AGENT_PID" | grep -q ssh-agent; then
(umask 077; ssh-agent > "$environ")
source "$environ"
fi
### Option A: load my private key from a file (passphrase will be asked on terminal)
if ! ssh-add -T $HOME/.ssh/id_rsa.pub 2>/dev/null; then
ssh-add $HOME/.ssh/id_rsa
fi
### Option B: load the private key (and passphrase) from Lastpass
LPASS_LOGIN="my.email.address@my.domain"
LPASS_SSHKEY="12345678901234567890" # this is the Lastpass entry where my SSH key is saved
lpass status -q || lpass login --trust "$LPASS_LOGIN"
test -f "$HOME/.ssh/lpass_passphrase.sh" || echo '/usr/bin/lpass show $LPASS_SSHKEY --field="Passphrase"' > "$HOME/.ssh/lpass_passphrase.sh"
test -x "$HOME/.ssh/lpass_passphrase.sh" || chmod +x "$HOME/.ssh/lpass_passphrase.sh"
lpass show $LPASS_SSHKEY --field="Private Key" | SSH_ASKPASS="$HOME/.ssh/lpass_passphrase.sh" DISPLAY= ssh-add -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment