How to auto-update SSH agent environment variables when attaching to existing tmux sessions

sorin picture sorin · Jan 27, 2014 · Viewed 26.5k times · Source

I am trying to find a nice way to restore the SSH agent when I reconnect a disconnected tmux session.

The cause seems to be that the SSH agent session changes but the environment variable from the tmux session is not updated.

How can I automate this, before attaching the session itself? Because the session I am attaching to does not always have a bash prompt, so I cannot afford to type something inside it. It has to be something to run before creating or attaching the tmux session.

An example of the code I'm running is at https://gist.github.com/ssbarnea/8646491 -- a small ssh wrapper that is using tmux to create persistem ssh connections. This works quite well, but sometimes the ssh agent stops working so I am no longer able to use it to connect to other hosts.

Answer

pymkin picture pymkin · Apr 20, 2014

There's an excellent gist by Martijn Vermaat, which addresses your problem in great depth, although it is intended for screen users, so I'm adjusting it for tmux here.

To summarize:

  1. create ~/.ssh/rc if it doesn't exist yet, and add the following content:

    #!/bin/bash
    
    # Fix SSH auth socket location so agent forwarding works with tmux
    if test "$SSH_AUTH_SOCK" ; then
      ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
    fi
    
  2. Make it work in tmux, add this to your ~/.tmux.conf:

    # fix ssh agent when tmux is detached
    setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock
    

Extra work is required if you want to enable X11 forwarding, see the gist.