Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ssh-agent

tmux

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.

like image 257
sorin Avatar asked Jan 27 '14 10:01

sorin


People also ask

Does tmux inherit environment variables?

It gives the option to set tmux as the default shell, and spawn it directly. This way tmux does not inherit environment variables from shells.

Does tmux work over SSH?

With tmux you only need one SSH connection to the server. The great thing about tmux is it allows you to have multiple panes open at the same time, each with their own shell running, but using the same, single SSH connection.

What does SSH agent do?

The ssh-agent is a helper program that keeps track of user's identity keys and their passphrases. The agent can then use the keys to log into other servers without having the user type in a password or passphrase again. This implements a form of single sign-on (SSO).


1 Answers

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.

like image 102
pymkin Avatar answered Sep 20 '22 20:09

pymkin