steamsprocket.org.uk

Connecting a screen session to ssh-agent

GNU screen is an excellent way of keeping a persistent multi-terminal session for console based programs. It shines when connecting to a remote server – ssh in, run screen to create a session, then do whatever you want in it. At any point you can detach from the session and it will keep running in the background until you reattach it (or screen is killed for some reason; good luck maintaining a persistant session across reboots). This works even if your connection is reset by Pierre, or whatever.

An SSH authentication agent (such as ssh-agent or Pageant) is a similarly excellent way of securely ((As long as you trust root on any intermediate servers. For more on that look here, especially the section on ‘Agent Security Concerns’)) forwarding ssh authentication requests, allowing for something resembling single-sign-on between machines configured to accept your ssh key.

There is one problem however: the ssh client knows to connect to a running agent based on the environment variables the agent provides. On the other hand, screen inherits its environment from the shell that started it in the first place. When you reconnect, you are presented with exactly the environment you left, which has a different ssh-agent magic token – leaving ssh unable to find the agent.

Enter the following handy function:

function ssh-reagent () {
    for agent in /tmp/ssh-*/agent.*; do
        export SSH_AUTH_SOCK=$agent
        if ssh-add -l 2>&1 > /dev/null; then
            echo Found working SSH Agent:
            ssh-add -l
            return
        fi
    done
    . ~/.ssh-agent
    if ssh-add -l 2>&1 > /dev/null; then
        echo Found working SSH Agent:
        ssh-add -l
        return
    fi
    echo Cannot find ssh agent - maybe you should reconnect and forward it?
}

Which I got from this guy. Put this in your ~/.bashrc ((Or the equivalent for your shell of choice, if it acceps the same syntax)) and then you can type ‘ssh-reagent’ to set the appropriate environment variable. Alternatively, if you prefer a greater degree of automation, the author has a further development.

NB: My version has two differences to the original version in that post The first is a bugfix changing 2&>1 to 2>&1; see here if you don’t understand that. The second is to source ~/.ssh-agent; unfortunately I can’t remember doing that and I don’t seem to have a decent commit log for it, so I’ll be damned if I can remember what problem it fixed :P.

Leave a Response