SSH Agent forwarding with tmux

Most of the time i connect to remote virtial machine to SSH to other servers. This way i will always have a fixed IP, so i can white list my IP in firewall. I use tmux on this server, so even if i get disconnected, my connection to these servers won’t get disconnected. This is useful when you running some commands that take long to finish.

On this VPS, i don’t keep my SSH keys for security reason, instead i use SSH Agent forwarding with ssh -A option. From my PC, i connect to sshbox with command

ssh -A root@IP_OF_VM

If i start a new tmux session, i will be able to login to other servers using my SSH key. If i attach to pre extsing tmux session, my SSH key won’t work. This is because SSH Agent use an environment variable SSH_AUTH_SOCK, this point to a sock file. When you get disconnected, it get deleted.

To fix this problem, edit ~/.tmux.conf file

vi ~/.tmux.conf


set-environment -g 'SSH_AUTH_SOCK' ~/.ssh/ssh_auth_sock

Create file

vi ~/.ssh/rc

with following content

if [ ! -S ~/.ssh/ssh_auth_sock ] && [ -S "$SSH_AUTH_SOCK" ]; then
    ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock

~/.ssh/rc file get executed every time a user connect using SSH. It will set symlink to SSH_AUTH_SOCK location if SSH agent forwarding is enabled.

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *