Skip to content

Instantly share code, notes, and snippets.

@bcomnes
Last active May 22, 2024 21:11
Show Gist options
  • Save bcomnes/e756624dc1d126ba2eb6 to your computer and use it in GitHub Desktop.
Save bcomnes/e756624dc1d126ba2eb6 to your computer and use it in GitHub Desktop.
ssh agent forwarding in tmux and gnu screen
# Fix agent forwarding
# https://gist.github.com/martijnvermaat/8070533
# http://techblog.appnexus.com/2011/managing-ssh-sockets-in-gnu-screen/
# See .ssh/rc for socket linking
unsetenv SSH_AUTH_SOCK
setenv SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock.$HOSTNAME
#!/bin/bash
# http://techblog.appnexus.com/2011/managing-ssh-sockets-in-gnu-screen/
# https://gist.github.com/martijnvermaat/8070533
# http://stackoverflow.com/questions/21378569/how-to-auto-update-ssh-agent-environment-variables-when-attaching-to-existing-tm
# Fix SSH auth socket location so agent forwarding works with screen.
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock.$(hostname)
fi
# Don't break x11 Forwarding:
# Taken from the sshd(8) manpage.
if read proto cookie && [ -n "$DISPLAY" ]; then
if [ `echo $DISPLAY | cut -c1-10` = 'localhost:' ]; then
# X11UseLocalhost=yes
echo add unix:`echo $DISPLAY |
cut -c11-` $proto $cookie
else
# X11UseLocalhost=no
echo add $DISPLAY $proto $cookie
fi | xauth -q -
fi
# https://gist.github.com/admackin/4507371
# fix ssh agent when tmux is detached
# See .ssh/rc for socket linking
set -g update-environment -r
setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock.$HOSTNAME
@antifuchs
Copy link

I believe that tmux doesn't work might have to do with $HOSTNAME not being set everywhere? I did not have that variable set in my tmux server process, so it ended up looking in ~/.ssh/ssh_auth_sock.; using export HOSTNAME=$(hostname) before you start tmux does the trick, though.

I have seen no problems with re-attaching to a session either - ssh in tmux's child processes can just keep connecting to the same socket all the time; as long as the rc script runs when you connect to the host (which updates the symlink), you should be OK.

The only thing that will bite you is if you attach to a non-detached session: Only one session's SSH agent connection can be used, and it's always the last one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment