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.
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.
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.
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).
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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With