Last active
February 9, 2024 22:10
-
-
Save sinewalker/91d74a0d19a93f373e2071e5ba2ced2e to your computer and use it in GitHub Desktop.
ssh-pass: add an SSH key to your agent with passphrase from password store, no clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#Add specified SSH keys to the SSH Agent, using SSH_ASKPASS to retrieve | |
#each key's passphrase from the Unix password store (pass). | |
#This relies upon the keys having the same names in both your key directory | |
#and your password store. | |
if [[ -z ${1} ]]; then | |
echo "$(basename ${0}): no SSH key specified" 1>&2 | |
exit 1; | |
fi | |
KEY_DIR=${HOME}/key | |
export DISPLAY=dummy | |
for KEY in ${@}; do | |
export SSH_ASKPASS=$(mktemp -t ssh-askpass) | |
cat > ${SSH_ASKPASS} << EOF | |
#!/bin/sh | |
pass ${KEY}|head -1 | |
EOF | |
chmod +x ${SSH_ASKPASS} | |
ssh-add ${KEY_DIR}/${KEY} < /dev/null | |
rm ${SSH_ASKPASS} | |
done |
Automatically load ssh keys :
Add to .bashrc and configure environment variable.
export SSH_DIR="${HOME}/.ssh"
command mkdir -p "${SSH_DIR}"
eval "$(ssh-agent -s)" >/dev/null 2>&1
export SSH_AUTH_SOCK="${SSH_AUTH_SOCK}"
export SSH_AGENT_LIFE=14400 # 4 hours
export SSHADD_OPTS=""
export PASS_SSH_ENTRY_PREFIX="_ssh"
if command -v pass &>/dev/null \
&& command -v gpg &>/dev/null \
; then
for _public_key in "${SSH_DIR}"/*.pub ; do
_private_key="${_public_key%.pub}"
_entry="$(basename "${_private_key}")"
if command pass ls "${PASS_SSH_ENTRY_PREFIX}/${_entry}" &>/dev/null ; then
if ! command ssh-add -l | command grep -qF -- "$(command ssh-keygen -lf "${_public_key}")" &>/dev/null ; then
_ask="${SSH_DIR}/ssh-askpass.sh"
(\
echo '#!/usr/bin/env -S bash -euo pipefail' ; \
echo ; \
echo "command pass '${PASS_SSH_ENTRY_PREFIX}/${_entry}/password' | command head -n 1" \
) > "${_ask}"
command chmod u+x "${_ask}"
DISPLAY="${DISPLAY:-dummy}" \
SSH_ASKPASS_REQUIRE=force \
SSH_ASKPASS="${_ask}" \
command ssh-add -t "${SSH_AGENT_LIFE}" ${SSHADD_OPTS:-} "${_private_key}"
fi
fi
done
command rm -f "${_ask}"
unset _public_key _private_key _entry _ask
#echo ; ssh-add -l
fi
My pass ssh entries:
$ pass _ssh/
_ssh
└── id_termux
├── cipher
├── note
├── password
├── privateKey.priv
└── publicKey.pub
...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also now a shell function in my dotfiles setup
EDIT 2022-02-17:
Now on GitLab:
https://gitlab.com/milohax-net/radix/bashing/-/blob/02a75e71f7eb44512d022081052ed564067d1e1f/modules/31_ssh.sh#L26-67
And a Fish version:
https://gitlab.com/milohax-net/radix/fishing/-/blob/4cb055d9fcf4f5338d749c16f7e121ff283d04bd/functions/ssh-pass.fish