Can I re-attach SSH key forwarding through a disconnected Screen session? [duplicate]

My solution is a bit more robust. Put this in your .bash_profile on the remote side.

if [ -z "${STY}" -a -t 0 ]; then
    reattach () {
        if [ -n "${SSH_AUTH_SOCK}" ]; then
            ln -snf "${SSH_AUTH_SOCK}" "${HOME}/.ssh/agent-screen"
            SSH_AUTH_SOCK="${HOME}/.ssh/agent-screen" export SSH_AUTH_SOCK
        fi
        exec screen -A -D -RR ${1:+"$@"}
    }
fi

Then I use reattach instead of screen. This could be done using command screen -A ${1:+"$@"} and 'screen' instead of 'reattach'.

The problem with using the 'alias' solution in the answer by @David Mackintosh is that the processes running in screen now have the same SSH_AUTH_SOCK value on the remote side. Think of the following scenerio.

  • local: start SSH agent getting SSH_AUTH_SOCK value
  • local: SSH to remote, setting new SSH_AUTH_SOCK value on remote
  • remote: start screen or tmux, using SSH_AUTH_SOCK
  • remote: create shell, which inherits SSH_AUTH_SOCK from screen
  • remote: detach from screen and log out
  • local: SSH to remote, setting new SSH_AUTH_SOCK value on remote
  • remote: reattach to screen session, which still has old SSH_AUTH_SOCK value

The trick is to get the processes running inside screen to use the new value. You can do that by repointing a symlink to the current SSH_AUTH_SOCK each time you call screen (for new or reattached session).


This is actually a duplicate of: ssh-agent key timeout with screen or tmux on bastion host

The solution:

  • add to your .bash_profile:

    echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" > ~/.ssh/auth_sock

  • add to your .bashrc:

    alias ssh="source ~/.ssh/auth_sock ; ssh"

This seems to work so far for me.