Linux – Attach a tmux session to a remote machine

linuxsshtmux

I am using tmux on my local machine and usually have several sessions simultaneously.

What I usually do is I have a session with different windows to work locally and the other sessions in which I connect several windows to one host per session.

A session / window tree would look like this in the daily use I make of tmux:

(TMUX on my local machine)
 |
 +- session 1: local
 |  \_ window 1: local shell
 |  \_ window 2: local shell
 |  \_ ...
 |
 + session 2: somehost
 |  \_ window1: ssh user@somehost
 |  \_ window2: ssh user@somehost
 |  \_ ...
 |
 + session 3: someotherhost
    \_ window1: ssh user@someotherhost
    \_ window2: ssh user@someotherhost
    \_ ...

Is there a way to make session 2 & session 3 some sort of remote sessions connecting to a tmux session created on somehost & someotherhost?

The above tree would look like this:

(TMUX on my local machine)
 |
 +- session 1: local
 |  \_ window 1: local shell
 |  \_ window 2: local shell
 |  \_ ...
 |
 + session 2 linked to an existing session on somehost
 |  \_ window1: shell on somehost
 |  \_ window2: shell on somehost
 |  \_ ...
 |
 + session 3 linked to an existing session on someotherhost
    \_ window1: shell on someotherhost
    \_ window2: shell on someotherhost
    \_ ...

I found this topic but I am not sure this is what I want to do: Is sharing a tmux sockets between hosts possible?

I suppose what I am looking for would require me to have the same tmux configuration on my local machine, somehost & someotherhost but that would not be a problem.

Best Answer

You can pass a command to ssh when connecting to a remote host. Include the -t option with tmux attach-session to connect to the remote tmux session:

ssh <remote host> -t tmux attach-session

This post on attaching to a tmux session via ssh explains it in more detail.

Related Question