14

I'm connecting through SSH from a machine where my keys are stored, forwarding to a second machine, and then try to use the keys from within tmux. I appear to "loose" the forwarding when entering tmux. How can "forward again" so that I can use my keys from within tmux?

$ ssh [server] -o ForwardAgent=yes
$ git pull       # Succeeds.
$ /bin/bash
$ git pull       # Still succeeds, despite new shell.
$ exit
$ tmux attach
$ git pull       # Permission denied (publickey)
11

If you're attaching an already existing tmux session, the shell is not inheriting the environment variables from your login shell. Particularly, it won't inherit the ssh agent environment variables.

Try this fix:

  1. Create this script and put it in $HOME/.ssh/saveagent

    #!/bin/sh
    SSHVARS="SSH_CLIENT SSH_TTY SSH_AUTH_SOCK SSH_CONNECTION DISPLAY"
    
    for var in ${SSHVARS} ; do
      echo "export $var=\"$(eval echo '$'$var)\""
    done 1>$HOME/.ssh/latestagent
    
  2. Add it to your shell startup script. For instance if you use bash:

    echo '. ~/.ssh/saveagent' >> ~/.bash_login
    
  3. After attaching the tmux, run . $HOME/.ssh/latestagent

See also How can I run a script immediately after connecting via SSH? and Attach to tmux session and run a command

  • 1
    Send to .profile maybe, if you're trying to be compatible with other sh shells. – Dereckson Feb 11 '14 at 1:19
  • 1
    Great answer! A few issues I ran into: a - some of the environment variables contain spaces, so the line before last in the saveagent script should be: echo "export $var=\"$(eval echo '$'$var)\"". b - the latestagent script should be called with source instead of sh, so setting the variables will affect the calling shell. c - calling the latestagent script automatically upon attaching tmux can be done via the method described here: unix.stackexchange.com/questions/86925/… – Joe Oct 14 '14 at 10:53
  • Thanks @Joe, I modified my answer to include your improvements. – GnP Oct 16 '14 at 3:47
0

Unless you want to source a script containing all the variables you need in every shell you further spawn in any new shell spawned by the same tmux server sessions, you will probably want to tell tmux to put the variables into the session or global environments with the set-environment command. For example like this (for bash):

for var in DISPLAY SSH_AUTH_SOCK ...; do
    tmux setenv "$var" "${!var}"
done

remember to add the -g flag if you want it in other sessions as well and to use -t <session> if you are running it from outside of tmux.

0

After reading the other answers here, I decided to just copy my public/private keypair to the remote server, so that I didn't need to worry about agent forwarding anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.