Categories
SysAdmin

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
        fi
    done
    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"
fi

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.