Moving an SSH Session to TMUX

If you are a regular user of tmux on the shell, I ‘m sure you been at the following point before as well:

I have logged into a remote host over ssh and started a long running command. I usually start a remote tmux session first, so I can close my notebook and cut the connection at any time if necessary. No harm done, the long running command continues running and I can come back to it at any time by attaching to the remote tmux session again. Every now and then, however, I forget to start tmux before that long running command, so I’m stuck and can’t close the notebook if I want the command to continue running on the remote host.

When this happened to me again recently, I wondered if I could move this ssh session to a new tmux session while the long running command is already active. And it turns out that this is actually possible!

The command to move a terminal session to another terminal session, i.e. a remote tmux session in this case, is reptyr, which stands for ‘reparenting terminal sessions’. So here’s how to use it:

Reptyr is not installed by default, but it’s in the official Debian repository, so it can be installed with a simple ‘sudo apt install reptyr‘. Then open a new ssh session to that remote host and start a remote tmux session inside. Next, find the parent process id (PPID) of the terminal session with that long running command you want to transfer into your remote tmux session:

# 1. ssh into the remote host
#
# 2. start a tmux session

# In the new tmux session:
#
ps -ef | grep '[s]shd:'

# find the pts/x line that matches, e.g. pts/0, pts/1, etc.
#
# Now find the terminal and its parent thread (PPID):
# replace pts/0 with the real one:
#
ps -t pts/XXXX -o ppid,stat,cmd

# cmd will show the currently running shell command
#
# Take note of the PPID

# Now move the terminal into the tmux session
#
sudo reptyr -T <PPID>

Looks like a lot to do, but that’s just the comments, it’s really just 3 commands:


ps -ef | grep '[s]shd:'

ps -t pts/XXXX -o ppid,stat,cmd

sudo reptyr -T <PPID>

After the reptyr command, the terminal and the long running command inside it are in the tmux session now. All new output will be sent there. The original ssh terminal session is frozen, even pressing ENTER will not move the cursor there anymore. Hence it can be closed, e.g. with ALT+~ followed by a ‘.’ character.

Really neat!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.