You can make a script for everyone's login process which
- checks if at least one ssh-agent instance is running (for this user)
- selects the instance to be used (the oldest)
- checks whether the socket info for this process is available (and correct)
- in case of success takes this info in its own environment
- and maybe kills the other instances (at least its own if there is one)
ps -o pid,etime,args --no-headers --sort=start_time \
-p $(pgrep --uid $USER ssh-agent) |
awk '{print $1; exit;}'
gives you the PID of the oldest ssh-agent instance. This would be easier with pgrep --uid $USER --oldest ssh-agent
but this way you easily get the PIDs of the other instances, too.
You could write $SSH_AUTH_SOCK
in a file ~/.ssh/env/$PID
(if $SSH_AGENT_PID
of the current process equals $PID):
echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" > ~/.ssh/env/$PID
Other sessions could check whether the file exists and is still valid and import it:
bash -c 'test -e ~/.ssh/env/$PID || exit 1;
. ~/.ssh/env/$PID; test -e $SSH_AUTH_SOCK' && . ~/.ssh/env/$PID
ssh-agent ssh host.example.com
then the agent cache will not be available to the session or other logins. Often the agent is child of the window manager so all children of that have access to the agent.