Skip to content

Instantly share code, notes, and snippets.

@kouk
Last active August 29, 2015 14:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kouk/0523b996b73563dbd487 to your computer and use it in GitHub Desktop.
Save kouk/0523b996b73563dbd487 to your computer and use it in GitHub Desktop.
connect with gpg-agent (with ssh) at all costs
# Tries to connect to a running gpg-agent or starts one itself. It tries connecting to:
# 1. the agent currently designated in the environment,
# 2. the agent designated in the $HOME/.gnupg/gpg-agent-info file,
# 3. the most recently started running gpg-agent process, or last
# 4. a new gpg-agent process, with ssh support and, if applicable, x11 support.
#
# Step no. 3 requires the "pgrep" and "sockstat" utilities (available on FreeBSD)
CONNECTGPG=$(which gpg-connect-agent)
if [ -x $CONNECTGPG ] ; then
agent_info=$HOME/.gnupg/gpg-agent-info
validate_agent () {
if env GPG_AGENT_INFO=$GPG_AGENT_INFO \
$CONNECTGPG /bye >/dev/null 2>&1 ; then
export GPG_AGENT_INFO SSH_AUTH_SOCK \
SSH_AGENT_PID GPG_TTY=$(tty)
return 0
fi
return 1
}
for _ in "" ; do
validate_agent && break
if [ -f $agent_info ] ; then
. $agent_info
validate_agent && break
fi
agent_pid=""
if [ -x $(which pgrep) ] ; then
agent_pid=$(pgrep -o gpg-agent)
fi
if [ -n "$agent_pid" -a -x $(which sockstat) ] ; then
sockstat -u | grep "$agent_pid" | sed -e 's/.* //' \
-e "s/.*gpg-agent\$/GPG_AGENT_INFO=&:$agent_pid:1/" \
-e 's/.*gpg-agent.ssh$/SSH_AUTH_SOCK=&/' > $agent_info
echo "SSH_AGENT_PID=$agent_pid" >> $agent_info
. $agent_info
validate_agent && break
fi
eval $(gpg-agent --sh --daemon ${DISPLAY:+--display $DISPLAY} \
--enable-ssh-support \
--write-env-file ${HOME}/.gnupg/gpg-agent-info)
validate_agent && break
done
unset agent_info agent_pid
unset -f validate_agent
fi
unset CONNECTGPG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment