X-Git-Url: http://git.iain.cx/?p=profile.git;a=blobdiff_plain;f=.profile.d%2Fssh.bashrc;h=17cd4bb01018e2240f88a1a75eaba2a7e99686b4;hp=9aac92cf30028280582ed5e75019ca46274685b2;hb=819bb88d5a014a23150b8fd609d194e883958674;hpb=7ff1edff9e3b22a1fd1f7798a634538d7ed94c54 diff --git a/.profile.d/ssh.bashrc b/.profile.d/ssh.bashrc index 9aac92c..17cd4bb 100644 --- a/.profile.d/ssh.bashrc +++ b/.profile.d/ssh.bashrc @@ -1,3 +1,9 @@ +SOCKET=~/.ssh/agent + +function get_agent_pid() { + ps waux | grep -- ^$USER\ .\*ssh-agent\ -a\ .\*\ -s | grep -v grep | awk '{ print $2 }' | head -n 1 +} + if [ ! -z "$SSH_CLIENT" ]; then # Set display if we aren't already forwarding X11 if [ "$DISPLAY" = "" ]; then @@ -7,19 +13,34 @@ fi # Try to hook up with already running ssh-agent. if [ $UID -gt 0 ]; then - RUNNING_AGENT="$(ps waux | grep -- ^$USER\ .\*ssh-agent\ -s | grep -v grep | awk '{ print $2 }' | head -n 1)" + # Not all OSes support ``ps -wu''. + RUNNING_AGENT="$(get_agent_pid)" + + # Has the socket gone away? + if [ ! -z "$RUNNING_AGENT" -a ! -S "$SOCKET" ]; then + if kill $RUNNING_AGENT; then + RUNNING_AGENT="$(get_agent_pid)" + else + echo >&2 "$SOCKET has gone away but agent is running as PID $RUNNING_AGENT." + fi + fi + if [ -z "$SSH_AGENT_PID" -o ! "$SSH_AGENT_PID" = "$RUNNING_AGENT" ]; then export SSH_AGENT_PID="$RUNNING_AGENT" if [ "$SSH_AGENT_PID" = "" ]; then unset SSH_AGENT_PID unset SSH_AUTH_SOCK # Start ssh-agent up then. - eval $(/usr/bin/ssh-agent -s) + rm -f "$SOCKET" + eval $(/usr/bin/ssh-agent -a "$SOCKET" -s) trap "kill $SSH_AGENT_PID" 0 ssh-add else - export SSH_AUTH_SOCK="/$(lsof -p $SSH_AGENT_PID | grep 'agent.[0-9]*$' | cut -s -d / -f 2-)" + export SSH_AUTH_SOCK="$SOCKET" fi fi unset RUNNING_AGENT fi + +unset SOCKET +unset get_agent_pid