How to Stop Ubuntu from Automatically Closing Idle SSH Sessions

The Disconnected Pipeline

When you use an Ubuntu machine (or server) to connect to another system via SSH (Secure Shell), the connection is designed to be persistent. However, network routers, firewalls, and NAT (Network Address Translation) devices sit between you and the remote server. If you leave your SSH terminal open but do not type anything for several minutes, these intermediary network devices might assume the connection is dead and drop the routing tables to save memory. When you return to your terminal and try to type, you are greeted with a frozen screen or a “Write failed: Broken pipe” error, meaning Ubuntu has automatically closed the idle SSH session.

Implementing Keep-Alive Packets

To maintain a persistent connection through aggressive firewalls and stop Ubuntu from automatically closing your idle SSH sessions, you must configure the SSH client to send regular “heartbeat” packets.

You need to modify your local user’s SSH configuration file. Open a terminal (Ctrl+Alt+T) and type nano ~/.ssh/config. (If the file or directory does not exist, Nano will create it for you). In the text editor, add the following lines at the very top of the file to apply the rules globally to all SSH connections:
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
The `ServerAliveInterval 60` directive tells your Ubuntu machine to silently send a null packet to the remote server every 60 seconds. This packet contains no real data, but it generates enough network traffic to convince the routers and firewalls that the connection is still active and in use. Press Ctrl+O then Enter to save, and Ctrl+X to exit Nano. All future SSH sessions will now stay alive indefinitely, even if left idle.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.