How to automatically update SSH agent environment variables when connecting to existing tmux sessions

I am trying to find a good way to recover an SSH agent when reconnecting a disconnected tmux session.

The reason is that the SSH agent session is changing, but the environment variable from the tmux session is not being updated.

How can I automate this before attaching the session itself? Since the session I am attached to does not always have a bash prompt, so I cannot allow myself to type anything inside it. This should be something that needs to be done before creating or joining a tmux session.

Sample code that I run is located at https://gist.github.com/ssbarnea/8646491 , a small ssh wrapper that uses tmux to create a persistent ssh connection. This works pretty well, but sometimes the ssh agent stops working, so I can no longer use it to connect to other hosts.

+45
ssh-agent tmux
Jan 27 '14 at 10:36
source share
4 answers

There is an excellent gist Martijn Vermaat, which solves your problem in great detail, although it is intended for screen users, so I configure it for tmux here.

Summarizing:

  • create ~/.ssh/rc if it does not already exist 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 it to your ~/.tmux.conf :

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

More work is needed if you want to enable X11 forwarding, see gist .

+53
Apr 20 '14 at 20:07
source share
— -

While tmux updates SSH variables by default, there is no need

  • change / add socket path
  • change the variable SSH_AUTH_SOCKET

I like the Chris Down solution that I changed to add a feature

 fixssh() { eval $(tmux show-env \ |sed -n 's/^\(SSH_[^=]*\)=\(.*\)/export \1="\2"/p') } 

in ~/.bashrc . Call fixssh after joining the session or before SSH / scp / rsync .

Newer versions of tmux support -s for show-env , so only

 eval $(tmux show-env -s |grep '^SSH_') 

perhaps.

+13
Jan 08 '16 at 18:21
source share

Here I use to update SSH_AUTH_SOCK inside the tmux window (based on the Hans Ginzel script):

 alias fixssh='eval $(tmux showenv -s SSH_AUTH_SOCK)' 

Or for tmux that does not have showenv -s :

 alias fixssh='export $(tmux showenv SSH_AUTH_SOCK)' 
+4
Dec 05 '16 at 5:38
source share

Here is my solution that includes both approaches and does not require additional configuration when reconnecting to a tmux session

 alias ssh='[ -n "$TMUX" ] && eval $(tmux showenv -s SSH_AUTH_SOCK); /usr/bin/ssh' 
+2
Jun 09 '17 at 20:18
source share



All Articles