DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Re-use Existing Ssh-agent

04.03.2010
| 3729 views |
  • submit to reddit
        // dot this script, don't just run it as a script (which would run it in its own sub-shell) because you need the variables to be set in the context of your current shell.

#!/bin/bash

for FILE in $(find /tmp/ssh-???*[0-9]* -type s -user ${LOGNAME} -name "agent.[0-9]*")
do

    GOT_AGENT=0

    SOCK_PID=${FILE##*.}

    PID=$(ps -fu${LOGNAME}|awk '/ssh-agent/ && ( $2=='${SOCK_PID}' || $3=='${SOCK_PID}' || $2=='${SOCK_PID}' +1 ) {print $2}')

    SOCK_FILE=${FILE}

    SSH_AUTH_SOCK=${SOCK_FILE}; export SSH_AUTH_SOCK;
    SSH_AGENT_PID=${PID}; export SSH_AGENT_PID;

    ssh-add -l | grep : > /dev/null
    if [ $? = 0 ]
    then
        GOT_AGENT=1
        echo "Agent pid ${PID}"
        break
    fi
    echo "Skipping pid ${PID}"

done

if [ $GOT_AGENT = 0 ]
then
    ssh-add
fi

Before I used the find I was using this, but it's not as accurate, and the socket file is more important than the PID when you're trying to connect to an existing agent, so it makes sense to me to start with that.
(unless your find would be horribly slow for some reason)

for PID in $(ps -furoot | awk '/ssh-agent/{print $2}')
do
    let SOCK_PID=PID-1
    SOCK_FILE=$(ls -d /tmp/ssh-???*${SOCK_PID}/agent.${SOCK_PID})

Also see: http://snippets.dzone.com/posts/show/8187

I add this to .bashrc / .kshrc

alias ssh_agent='. $HOME/.ssh/ssh_agent'