Skip to content

Instantly share code, notes, and snippets.

@blaffoy
Created January 9, 2017 15:20
Show Gist options
  • Save blaffoy/e688d71f4d37ddddbae2714f91305a0f to your computer and use it in GitHub Desktop.
Save blaffoy/e688d71f4d37ddddbae2714f91305a0f to your computer and use it in GitHub Desktop.
Bash script to find a load running ssh-agent authorization sockets
#!/bin/bash
function check_agent_socket() {
local SOCKET=$1
SSH_AUTH_SOCK=$SOCKET ssh-add -l 2> /dev/null > /dev/null
result=$?
case $result in
0)
IDENTITIES=$(SSH_AUTH_SOCK=$SOCKET ssh-add -l 2> /dev/null | awk '{print $3}')
echo "Socket $SOCKET has $(echo $IDENTITIES | wc -w) loaded identities \"$IDENTITIES\""
_LIVE_SOCKETS+=($SOCKET)
;;
1)
echo "Socket $SOCKET is alive, but has no load identities"
_LIVE_SOCKETS+=($SOCKET)
;;
2)
echo "Unable to contact agent for $SOCKET, removing"
rm -rvf $(dirname $SOCKET)
;;
esac
}
function find_ssh_agent_sockets() {
_SSH_AGENT_SOCKETS=$(find /tmp -maxdepth 1 -user $(whoami) -type d -name ssh* 2> /dev/null | \
xargs -I {} find {} -name agent.\* 2> /dev/null | \
grep '\/tmp\/ssh-.*\/agent\..*')
}
function select_ssh_agent_socket() {
_LIVE_SOCKETS=()
find_ssh_agent_sockets
if [ ! -z "$_SSH_AGENT_SOCKETS" ]
then
for sock in $_SSH_AGENT_SOCKETS
do
check_agent_socket $sock
done
fi
local N_LIVE_SOCKETS=${#_LIVE_SOCKETS[@]}
local N_LIVE_AGENTS=$(ps | grep [s]sh-agent | wc -l)
if [ "$N_LIVE_AGENTS" -ne "$N_LIVE_SOCKETS" ]
then
echo "WARNING: There are \"$N_LIVE_AGENTS\" live ssh-agent processes, but \"$N_LIVE_SOCKETS\" ssh auth sockets that can be connected"
fi
case $N_LIVE_SOCKETS in
0)
echo "No running ssh-agent found, launching one"
eval $(ssh-agent)
ssh-add -l
;;
1)
echo "Found a running ssh auth sock"
export SSH_AUTH_SOCK=${_LIVE_SOCKETS[0]}
ssh-add -l
;;
*)
echo -e "\nFound multiple live auth sockets, please choose one:"
for i in "${!_LIVE_SOCKETS[@]}"
do
printf "%s )\t%s\n" "$i" "${_LIVE_SOCKETS[$i]}"
done
read USER_SELECTION
export SSH_AUTH_SOCK=${_LIVE_SOCKETS[$USER_SELECTION]}
ssh-add -l
;;
esac
}
function main() {
select_ssh_agent_socket
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment