Recover from a lost remote shell

tmux is a very nice terminal multiplexer, is a good replacement for the old screen, but with many more features, you can have multiple virtual terminals in the same windows with the window splitted bet

tmux logo

ween them. (Until four or eighteen as you like).

It’s great, in the case if you are using a command that it will take too much time to complete, like a software upgrade using the apt tool.

You can go on with your work in the shell by doing Ctrl+B (in screen it was Ctrl+A), and the virtual terminal will detach from you console and you can return there later and see the later output. Sometimes when I login remotely using SSH from a low bandwidth connection like the one made from a mobile wireless 3G, the connection is unstable and most certainly the terminal session will be lost. One way to avoid this is to force a creation of a new virtual terminal in tmux everytime you connect with SSH.

With the script:

tmux has-session -t $LABEL
if [ $? == 1 ]
echo "Creating new tmux shell $LABEL"
tmux new -s $LABEL
echo "Attaching to already existing shell $LABEL"
tmux attach -t $LABEL

save this one as for example in your $homedir with name

then, inside the /etc/sshd_config file append the following snippet:

Match User <mylogin>
ForceCommand /home/<mylogin>/

This way, in the case if you lose your SSH connection you can restart from where you were by simply making a new connection with your ssh client (unix ssh command, putty, mobaxterm, etc.), the shell running inside the tmux container will be resumed from the point where you were. In the case if you have physical access to the remote computer you can access the terminal that was create for the ssh session by using the command:

tmux attach -t ssh_<mylogin>