Is there a convenient way to ensure that all logins from a given user (ie me) use the same ssh-agent? I hacked out a script to make this work most of the time, but I suspected all along that there was some way to do it that I had just missed. Additionally, since that time there have been amazing advances in computing technology, like for example this website.

So the goal here is that

  • whenever I log in to the box, regardless of whether it's via SSH, or in a graphical session started from gdm/kdm/etc, or at a console:
    • if my username does not currently have an ssh-agent running, one is started, the environment variables exported, and ssh-add called.
    • otherwise, the existing agent's coordinates are exported in the login session's environment variables.

This facility is especially valuable when the box in question is used as a relay point when sshing into a third box. In this case it avoids having to type in the private key's passphrase every time you ssh in and then want to, for example, do git push or something.

The script given below does this mostly reliably, although it botched recently when X crashed and I then started another graphical session. There might have been other screwiness going on in that instance.

Here's my bad-is-good script. I source this from my .bashrc.

# ssh-agent-procure.bash
# v0.6.4
# ensures that all shells sourcing this file in profile/rc scripts use the same ssh-agent.
# copyright me, now; licensed under the DWTFYWT license.

mkdir -p "$HOME/etc/ssh";

function ssh-procure-launch-agent {
    eval `ssh-agent -s -a ~/etc/ssh/ssh-agent-socket`;
    ssh-add;
}

if [ ! $SSH_AGENT_PID ]; then
  if [ -e ~/etc/ssh/ssh-agent-socket ] ; then
    SSH_AGENT_PID=`ps -fC ssh-agent |grep 'etc/ssh/ssh-agent-socket' |sed -r 's/^\S+\s+(\S+).*$/\1/'`; 
    if [[ $SSH_AGENT_PID =~ [0-9]+ ]]; then
      # in this case the agent has already been launched and we are just attaching to it. 
      ##++  It should check that this pid is actually active & belongs to an ssh instance
      export SSH_AGENT_PID;
      SSH_AUTH_SOCK=~/etc/ssh/ssh-agent-socket; export SSH_AUTH_SOCK;
    else
      # in this case there is no agent running, so the socket file is left over from a graceless agent termination.
      rm ~/etc/ssh/ssh-agent-socket;
      ssh-procure-launch-agent;
    fi;
  else
    ssh-procure-launch-agent;
  fi;
fi;

Please tell me there's a better way to do this. Also please don't nitpick the inconsistencies/gaffes ( eg putting var stuff in etc ); I wrote this a while ago and have since learned many things.

link|improve this question

48% accept rate
1  
KeyError: 'DWTFYWT' not found; did you mean WTFPLv2? – grawity May 14 '10 at 18:53
@grawity: thanks for that link, their FAQs made my day: By the way, with the WTFPL, can I also… Oh but yes, of course you can. But can I… Yes you can. Can… Yes! hahahahahaha – quack quixote May 14 '10 at 19:06
@grawity: No, that's just what I wanted you to think, mwahahaha. – intuited May 14 '10 at 20:58
feedback

5 Answers

up vote 5 down vote accepted

I might as well throw my own variation into the mix:

function sshagent_findsockets {
    find /tmp -uid $(id -u) -type s -name agent.\* 2>/dev/null
}

function sshagent_testsocket {
    if [ ! -x "$(which ssh-add)" ] ; then
        echo "ssh-add is not available; agent testing aborted"
        return 1
    fi

    if [ X"$1" != X ] ; then
        export SSH_AUTH_SOCK=$1
    fi

    if [ X"$SSH_AUTH_SOCK" = X ] ; then
        return 2
    fi

    if [ -S $SSH_AUTH_SOCK ] ; then
        ssh-add -l > /dev/null
        if [ $? = 2 ] ; then
            echo "Socket $SSH_AUTH_SOCK is dead!  Deleting!"
            rm -f $SSH_AUTH_SOCK
            return 4
        else
            echo "Found ssh-agent $SSH_AUTH_SOCK"
            return 0
        fi
    else
        echo "$SSH_AUTH_SOCK is not a socket!"
        return 3
    fi
}

function sshagent_init {
    # ssh agent sockets can be attached to a ssh daemon process or an
    # ssh-agent process.

    AGENTFOUND=0

    # Attempt to find and use the ssh-agent in the current environment
    if sshagent_testsocket ; then AGENTFOUND=1 ; fi

    # If there is no agent in the environment, search /tmp for
    # possible agents to reuse before starting a fresh ssh-agent
    # process.
    if [ $AGENTFOUND = 0 ] ; then
        for agentsocket in $(sshagent_findsockets) ; do
            if [ $AGENTFOUND != 0 ] ; then break ; fi
            if sshagent_testsocket $agentsocket ; then AGENTFOUND=1 ; fi
        done
    fi

    # If at this point we still haven't located an agent, it's time to
    # start a new one
    if [ $AGENTFOUND = 0 ] ; then
        eval `ssh-agent`
    fi

    # Clean up
    unset AGENTFOUND
    unset agentsocket

    # Finally, show what keys are currently in the agent
    ssh-add -l
}

alias sagent="sshagent_init"

And then every time I log in, if I want an agent attached (which I don't always), I just type sagent.

link|improve this answer
if [ ! -x "$(which ssh-add)" ]; should be replaced with if ! which ssh-add; or if ! command -v ssh-add. (Remember, [ is just a command) – grawity May 14 '10 at 19:13
Well, you can do that, but it would actually need to be if ! which ssh-add > /dev/null to prevent the path from being printed, at which point I'm not really sure it's any clearer, though I suppose it does save you one extra command invocation. – Zed May 14 '10 at 20:32
so basically the answer is no, then. crap. Well this looks to be more evolved than my hack, so probably it will be useful. Weird that there's not a more structured way of doing this though, it seems like something that would be quite useful. – intuited May 14 '10 at 20:56
I'm in a fit of repositorifying everything these days, so I set up a github repo for your script. Thanks again. I hope I was formal enough with the licensing :~/ – intuited Jul 27 '10 at 2:03
I don't mind. Please comment here if someone submits improvements to it, though. – Zed Aug 27 '10 at 19:37
feedback

Here's a pretty nice one that works in Cygwin as well:

SSH_ENV=$HOME/.ssh/environment

function start_agent {
     echo "Initialising new SSH agent..."
     /usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
     echo succeeded
     chmod 600 ${SSH_ENV}
     . ${SSH_ENV} > /dev/null
     /usr/bin/ssh-add;
}

# Source SSH settings, if applicable

if [ -f "${SSH_ENV}" ]; then
     . ${SSH_ENV} > /dev/null
     #ps ${SSH_AGENT_PID} doesn't work under cywgin
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
         start_agent;
     }
else
     start_agent;
fi

Add it to your .bash_profile or .bashrc

Source: http://www.cygwin.com/ml/cygwin/2001-06/msg00537.html

link|improve this answer
feedback

ssh -A [user@]remotehost

I think this might be what you're looking for. Use the -A switch when running ssh forward your ssh-agent. Here's a usecase:

I have a remote server that has some git repos on it with a remote pointing to github. Without an ssh-agent running in a screen session, I have to enter the passphrase for my key in order to do a "git pull origin master". Booo! In addition, I must have my private key installed on the remote server - more Boooo!

Instead, simply using ssh -A [user@]remotehost passes along my locally running ssh-agent. Now, I no longer need my private key to even exist on the remote host. I don't believe you need to do any scripting at all with ssh-agent.

link|improve this answer
This is what I was looking for, thx! – tmow Aug 18 '11 at 7:26
Did not know about this, but it turned out to be exactly what I was looking for when I made my way to this question. – Will McCutchen Nov 17 '11 at 14:34
feedback

I prefer to keep things as simple as possible: (snippet from ~/.profile)

check-ssh-agent() {
    [ -S "$SSH_AUTH_SOCK" ] && { ssh-add -l >& /dev/null || [ $? -ne 2 ]; }
}

# attempt to connect to a running agent
check-ssh-agent || export SSH_AUTH_SOCK="$(< ~/.tmp/ssh-agent.env)"
# if agent.env data is invalid, start a new one
check-ssh-agent || {
    eval "$(ssh-agent -s)" > /dev/null
    echo "$SSH_AUTH_SOCK" > ~/.tmp/ssh-agent.env
}

I didn't think of using -a before, but it might be easier:

check-ssh-agent || export SSH_AUTH_SOCK=~/.tmp/ssh-agent.sock
check-ssh-agent || eval "$(ssh-agent -s -a ~/.tmp/ssh-agent.sock)" > /dev/null
link|improve this answer
feedback

Try using keychain, its made for that. http://www.gentoo.org/doc/en/keychain-guide.xml

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.