Background
Broken SSH sessions can be a pain in the butt because it disrupts your workflow. Broken SSH sessions may be a result of:
- An unreliable link
- A load balancer
- Broken communication
- Just bad internet
This article examines two methods for maintaining link quality, namely SSH options to keep the session alive, and Screen.
SSH Options to Keep SSH Sessions Alive
Use a file called config
in .ssh
to make all sessions more reliable:
~ cat .ssh/config Host * ServerAliveInterval 30 ServerAliveCountMax 1
Big thanks to @razed on MyBroadband’s forum for sharing this tip.
Introduction to Screen
Screen is a utility to maintain an SSH session on an unreliable or long running task link. Unreliable might be a slow ISP, a really small line, or any kind of situation where the connection oriented TCP/IP protocol doesn’t receive enough confirmations back. Some examples of long running tasks might be backups and restoration, file operations, or any other kind of search and replace.
The bottom line is that if you have a less than perfect internet connection, between A and B, or B and C, you might need screen.
Screen is a utility to maintain the connection you have with the server. It’s a pseudo connection, in other words, Screen is just a front-end to the SSH terminal but not the real thing. If the connection drops or breaks, you can simply re-attach to the “screen” and carry on where you left off.
It’s really simple to use.
TLDR;
How to use screen to avoid SSH sessions being disconnected on a unreliable link. Many ISPs use load balancing, or wireless, in which case SSH might break.
To avoid this issue, on the remote server:
1. SSH to server
2. screen
Now when the link breaks,
3. SSH back into server
4. screen -ls
to list all detached and attached sessions. What you’re after is the detached session.
Look for your screen session, called something like “detached” with a code. Now do:
5. screen -r [ID]
Longer explanation
You are performing long running tasks on a remote server, e.g. using VIM, but the terminal keeps on breaking because it’s an unreliable link.
Solution:
The Linux utility ‘screen’ is ideally suited for these situations.
Steps:
- Install screen on the remote server
- Start screen
- Do your work
- When you link breaks, reattach to your screens.
Additional Commands
If you want to kill running screen sessions, use the following command:
screen -X -S [ID] quit
More information
- https://mybroadband.co.za/forum/threads/axxess-isp-ssh-sessions-always-breaking-due-to-load-balancer.1117896/
- https://linuxize.com/post/using-the-ssh-config-file/
Additional reference:
https://linuxize.com/post/how-to-use-linux-screen/#reattach-to-a-linux-screen