SSH Agent in GNU Screen

When starting a GNU Screen session, the current SSH agent is passed through to the new virtual terminal.  As long as you do not disconnect from the screen session, SSH agent forwarding should continue to work as normal.

Once you disconnect from the screen session and end the SSH connection, the SSH agent settings in the screen session are no longer valid.  If you reconnect to the screen session using a new SSH connection, the SSH agent socket has changed.

To fix this problem, I added the following bit of code to my ~/.bashrc file:

if ! [ -S $SSH_AUTH_SOCK ] ; then
    # delete old/lingering agent files
    for i in `find /tmp/ssh-* -maxdepth 2 -name agent* -user $USER 2>/dev/null` ; do
        if ! [ -S $i ] ; then
            rm $i
    unset i
    # set agent string
    SSH_AUTH_SOCK="`find /tmp/ssh-* -maxdepth 2 -name agent* -user $USER 2>/dev/null  | head -n1`"
    echo "Set SSH_AUTH_SOCK to $SSH_AUTH_SOCK"

This code does the following:

  1. Checks if the current $SSH_AUTH_SOCK environment variable is a valid socket
  2. If not, delete all old SSH agent socket files that may be lingering
  3. Set the $SSH_AUTH_SOCK environment variable to the first valid SSH agent socket file found

I normally open new virtual terminals to do work and close them when I’m complete.  That way I always have a current environment for the applications to use.  If you’re someone that uses only one virtual terminal and leaves it running forever, this trick won’t work as well for you.

If you connect to a server using multiple SSH connections, there’s a chance that a new virtual terminal in the screen session could use the SSH agent socket from a different SSH connection.  If you disconnect the other SSH session, you may loose access to the SSH agent and need to open a new virtual terminal (or run source ~/.bashrc) to regain access to an SSH agent.

2 replies on “SSH Agent in GNU Screen”

For those of us that do keep sessions alive in screen, the solution is basically the same as your solution for it finding a different ssh agent. Put the chunk of code you gave for .bashrc in a file and simply source it when reconnecting.

One additional thing I have done since posting this: I wrap the whole code block in a function called ‘ssha’, and call ‘ssha’ at the end of my .bashrc to ensure it runs every time I connect. By having it wrapped in a function, I’m also able to simply type ‘ssha’ to reload the agent variable quickly without needing to source any files.

Leave a Reply

Your email address will not be published. Required fields are marked *