How to automatically start tmux on SSH session?

I have ten or so servers that I connect to with SSH on a regular basis. Each has an entry in my local computer's ~/.ssh/config file.

To avoid losing control of my running process when my Internet connection inevitably drops, I always work inside a tmux session. I would like a way to have tmux automatically connect every time an SSH connection is started, so I don't have to always type tmux attach || tmux new after I SSH in.

Unfortunately this isn't turning out to be as simple as I originally hoped.

  • I don't want to add any commands to the ~/.bashrc on the servers because I only want it for SSH sessions, not local sessions.
  • Adding tmux attach || tmux new to the ~/.ssh/rc on the servers simply results in the error not a terminal being thrown after connection, even when the RequestTTY force option is added to the line for that server in my local SSH config file.

Solution 1:

Server-side configuration:

To automatically start tmux on your remote server when ordinarily logging in via SSH (and only SSH), edit the ~/.bashrc of your user or root (or both) on the remote server accordingly:

if [[ -n "$PS1" ]] && [[ -z "$TMUX" ]] && [[ -n "$SSH_CONNECTION" ]]; then
  tmux attach-session -t ssh_tmux || tmux new-session -s ssh_tmux
fi

This command creates a tmux session called ssh_tmux if none exists, or reattaches to a already existing session with that name. In case your connection dropped or when you forgot a session weeks ago, every SSH login automatically brings you back to the tmux-ssh session you left behind.

Connect from your client:

Nothing special, just ssh user@hostname.

Solution 2:

Alright, I found a mostly satisfactory solution. In my local ~/.bashrc, I wrote a function:

function ssh () {/usr/bin/ssh -t "$@" "tmux attach || tmux new";}

which basically overwrites the ssh terminal function to call the built-in ssh program with the given arguments, followed by "tmux attach || tmux new".

(The $@ denotes all arguments provided on the command line, so ssh -p 123 user@hostname will be expanded to ssh -t -p 123 user@hostname "tmux attach || tmux new")

(The -t argument is equivalent to RequestTTY Force and is necessary for the tmux command.)