DEV Community

Cover image for Persistent SSH Sessions with Tmux

Persistent SSH Sessions with Tmux

Michael Okoko on March 26, 2019

Hello SSH The SSH (Secure Shell) is a widely used protocol that helps you drop into a remote system, do what you want to do, and get out...
Collapse
 
josefwells profile image
Josef Wells

I use 'mosh' for UDP based ssh, this allows me to have a persistent ssh to a host where I then launching my tmux sessions. Now if my connection falters (laptop WiFi/wired or otherwise) my ssh stays up and my tmux sessions are safe on the host.

Collapse
 
ncot_tech profile image
James

This is something I've been trying to do too, however I couldn't get your method to work on my setup (LXC containers inside Proxmox). It wouldn't create the initial tmux session.

However, I found this Stack Overflow question which has a useful answer:

stackoverflow.com/questions/343253...

Putting tmux new -A -s mySession in my .profile works.

I'm also using mosh to persist the connection when my PC goes to sleep.

Collapse
 
sndp487 profile image
Sandeep

I was getting sessions should be nested with care, unset $TMUX to force at the top of tmux when using tmux attach || tmux new. What happens is tmux also executes .bashrc/profile.

So now I use this:

if [[ ! "$TERM" =~ "screen" ]]; then
tmux attach -t default || tmux new -s default
fi

in my .bashrc

TERM is set to 'screen' in tmux environment.

Collapse
 
idoko profile image
Michael Okoko

Glad you got it to work, also, I've only heard praises for mosh. I should take it for a spin one of these days.

Collapse
 
darkflib profile image
Mike Preston

Turn on keepalives in ssh config...

autossh -M 0 -t user@host tmux new -s sessname -A

This allows me to roam across networks and seemlessly reconnect if the connection fails.

It works on my 120mile commute across multiple networks flawlessly... and across laptop sleeps.

Collapse
 
rizwankh profile image
Rizwan

Same here. I also use tmuxinator which is just awesome!

Collapse
 
optio50 profile image
optio50

Just like screen?

Collapse
 
idoko profile image
Michael Okoko

Yeah, though I personally prefer tmux to screen.