Skip to content

Instantly share code, notes, and snippets.

@nycksw
Last active June 6, 2025 16:44
Show Gist options
  • Select an option

  • Save nycksw/05a000206bc2fdae184a333163a6f1c5 to your computer and use it in GitHub Desktop.

Select an option

Save nycksw/05a000206bc2fdae184a333163a6f1c5 to your computer and use it in GitHub Desktop.
agent handler 🕵️
# Like keychain(1) but in 66 lines of bash.
SSH_AGENT_FILE="$HOME/.ssh/agent.$(hostname)"
# Validate agent: must have valid socket and identities.
agent_valid() {
[[ -S "${SSH_AUTH_SOCK}" ]] && ssh-add -l &>/dev/null
}
# Source saved agent file if no valid forwarded agent.
if ! agent_valid; then
if [[ -f "${SSH_AGENT_FILE}" ]]; then
# shellcheck source=/dev/null
. "${SSH_AGENT_FILE}" >/dev/null
if ! agent_valid; then
unset SSH_AUTH_SOCK SSH_AGENT_PID
fi
fi
fi
# Find the freshest valid socket explicitly by mod time.
agent_update() {
local sock
sock=$(find /tmp -maxdepth 2 -type s -name 'ssh-*' \
-printf '%T@ %p\n' 2>/dev/null | sort -n | tail -n1 | awk '{print $2}')
if [[ -z "${sock}" || ! -S "${sock}" ]]; then
echo "No valid forwarded SSH socket found."
return 1
fi
export SSH_AUTH_SOCK="${sock}"
}
# If in SSH session and current socket invalid, update it.
if [[ -n "${SSH_CONNECTION}" ]] && ! agent_valid; then
agent_update
fi
# Display agent info, verifying PID explicitly.
agent_desc() {
if [[ -n "${SSH_AGENT_PID}" ]] && kill -0 "${SSH_AGENT_PID}" 2>/dev/null; then
echo "pid ${SSH_AGENT_PID}"
elif [[ -n "${SSH_CONNECTION}" ]]; then
echo "fwd $(awk '{print $1}' <<< "${SSH_CONNECTION}")"
else
echo "no agent"
fi
}
fingerprints=$(ssh-add -l 2>&1)
rc=$?
case "${rc}" in
0)
echo "ssh-agent: $(agent_desc)"
echo "${fingerprints}"
;;
1)
echo "ssh-agent ($(agent_desc)) has no identities."
ssh-add || echo "ssh-add failed. Check your keys."
;;
*)
if ! agent_valid; then
echo "Starting new ssh-agent."
mkdir -p "$(dirname "${SSH_AGENT_FILE}")"
ssh-agent > "${SSH_AGENT_FILE}"
# shellcheck source=/dev/null
. "${SSH_AGENT_FILE}" >/dev/null
ssh-add || echo "ssh-add failed. Check your keys."
fi
;;
esac
# vim: set ft=bash :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment