Last updated: June 2025
When using SSH agent forwarding with tmux, SSH agent forwarding works fine when you first connect and create a tmux session, but breaks when you reconnect later. This happens because:
Happy ssh agent forwarding for tmux/screen provides a clever solution (another level of indirection, the universal problem solver!) when you want to persist agent forwarding across a single tmux session, but it fails when there are multiple tmux sessions because the different sessions clobber each other's indirection state.
The solution below adapts werat's solution to the case of multiple concurrently active tmux sessions.
Create stable symlinks that point to the current SSH agent socket, and have each tmux session use its own dedicated symlink.
Create this function in your local shell (add to ~/.bashrc or ~/.zshrc) or implement it as a shell script:
ssht() { if [ $# -lt 2 ]; then echo "Usage: ssht hostname session-name" return 1 fi HOSTNAME="$1" SESSION_NAME="$2" export TMUX_SESSION_NAME="$SESSION_NAME" ssh -A -t -o SendEnv=TMUX_SESSION_NAME "$HOSTNAME" \ "tmux new-session -A -s '$SESSION_NAME' -e TMUX_SESSION_NAME='$SESSION_NAME'" }
This function:
Create ~/.ssh/rc on the remote server:
if [ -S "$SSH_AUTH_SOCK" ] && [ -n "$TMUX_SESSION_NAME" ]; then ln -sf "$SSH_AUTH_SOCK" "$HOME/.ssh/ssh_auth_sock_$TMUX_SESSION_NAME" fi
Make it executable:
chmod +x ~/.ssh/rc
This script runs every time you SSH to the server and creates a session-specific symlink pointing to the current SSH agent socket. It receives the value of $TMUX_SESSION_NAME via the SSH SendEnv mechanism.
Add this to ~/.bashrc (or ~/.zshrc) on the remote server:
if [ -n "$TMUX" ] && [ -n "$TMUX_SESSION_NAME" ]; then if [ -S "$HOME/.ssh/ssh_auth_sock_$TMUX_SESSION_NAME" ]; then export SSH_AUTH_SOCK="$HOME/.ssh/ssh_auth_sock_$TMUX_SESSION_NAME" fi fi
This ensures that shells within tmux use the correct session-specific SSH agent socket. You want it in your shell's .rc file, not the .profile file, so that it executes in all new tmux windows/panes, and not just on login.
In order for the SendEnv mechanism to work, you must add this line to /etc/ssh/sshd_config on the remote server:
AcceptEnv TMUX_SESSION_NAME
Then restart the SSH daemon:
sudo systemctl restart sshd
If you do not have control of the remote sshd, then one hack is to rename TMUX_SESSION_NAME to something like LC_TMUX_SESSION_NAME, because the default sshd configuration allows passing through locale environment variables:
# Allow client to pass locale environment variables AcceptEnv LANG LC_*
Instead of using ssh -A hostname tmux ..., use the wrapper function:
# Create/attach to session "work" ssht myserver.com work # In another local terminal, create/attach to session "personal" ssht myserver.com personal # Create/attach to session "experiments" ssht myserver.com experiments
Each session gets its own dedicated SSH agent forwarding that won't be affected by other sessions connecting or disconnecting.