Thursday, February 16, 2012

Configuring GNU Screen or tmux: Retain ssh-agent access when a session is reattached

For those that use terminal multiplexers like screen or tmux a common problem is to "lose" your ssh-agent after ending an ssh session.

The Problem

1. ssh to a remote server and start the terminal multiplexer for the first time.

The terminal multiplexer starts and all your shells capture the value of SSH_AUTH_SOCK at that time.  You can access your agent because the value of the environment variable in each shell is current.

2. Detach from the terminal multiplexer and exit from your ssh session.

The multiplexer still running on the remote server (along with all your shells).

3. ssh to the remote server and reattach.

So now you've reattached, but the environment variable SSH_AUTH_SOCK in each of your running shells is out of date. As a result you can't access your ssh-agent from your shells unless you update SSH_AUTH_SOCK.

The Solution
  1. Open up the shell config file you store your aliases in. ie. vim ~/.bashrc
  2. Add an alias for screen or tmux that will transparently update the auth-sock location to the same location every time.
alias screen='ln -sf $SSH_AUTH_SOCK $HOME/.ssh-auth-sock; env SSH_AUTH_SOCK=$HOME/.ssh-auth-sock screen'
alias tmux='ln -sf $SSH_AUTH_SOCK $HOME/.ssh-auth-sock; env SSH_AUTH_SOCK=$HOME/.ssh-auth-sock tmux'