Persistent SSH connections with tmux

I administer a group of Amazon cloud instances and am constantly having to SSH in to update and monitor them. And for some reason (maybe because I live in the back of beyond) I often get really poor connections to IPs belonging to Amazon. So I get dropped connections with annoying regularity. If I’m doing something that takes a while, or if I have a number of sessions open, I can lose work, or have to spend more time reopening the sessions and restarting whatever monitoring I was doing.

I kept coming across recommendations for GNU Screen and could see that it could help in some way, but for some reason I wasn’t quite getting it. I couldn’t see where it would fit in what I was doing. I fiddled with it, and byobu to try to get to grips with the concept.

End result is that all servers now have tmux installed, with a couple of shells open at the usual directories that I access. Easily accomplished by installing from the repos, running tmux and ‘CTRL-b CTRL-c’ to open a new shell, then ‘CTRL-n CTRL-d’ to detach from tmux but leave it running for later.

sudo apt-get install tmux
tmux

On my home PC I use autossh to reconnect to broken SSH sessions, aliases for each connection that I use to attach to the running tmux session, and SSH config files that handle passwords.

sudo apt-get install autossh

vi .ssh/config
# Add an entry for your server
Host somsip
HostName somsip.com
User XXXXX
IdentityFile /home/mark/.pem/somsip.pem
ControlMaster auto
ControlPath ~/.ssh/socket-%r@%h:%p
AddressFamily inet
CheckHostIP no

vi ~/.bash_aliases
# Add a line to use autossh to connect
alias somsip='autossh somsip -t tmux -a'

# Reload the aliases
. ~/.bash_aliases

Now I can connect to any server with a short alias, and I will have a couple of shells open where I need them, and I can run long commands under tmux. If the connection drops, autossh will reconnect with the shells open where I left them. And if I chose to detach from the session with the intention of coming back later, I can ‘CTRL-b d’ which closes the SSH session.

So far, it’s working well. And it puts a lime green bar at the bottom of the shell so I know I’m in a server shell, which is helpful!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>