How to Stop Ubuntu from Automatically Disconnecting Inactive SSH Sessions

When you connect to a remote Ubuntu server via SSH (Secure Shell), you establish a persistent, encrypted tunnel. However, if you switch away from your terminal window to read documentation or answer an email, you might return ten minutes later to find your SSH session completely frozen. When you press a key, the terminal violently spits out a “Broken pipe” or “Connection reset by peer” error, automatically terminating your session.

This happens because intermediate network hardware (like your home router, corporate firewalls, or the server’s NAT gateway) aggressively monitors active TCP connections. If the router does not see any data packets flowing through the SSH tunnel for a few minutes, it automatically assumes the connection is dead and silently drops the routing table to save memory. When you finally try to type a command, the server never receives it.

You can force your local SSH client to automatically send “keep-alive” packets—tiny, invisible pings—every few seconds to trick the router into keeping the connection open indefinitely.

How to Keep SSH Sessions Alive Automatically

You must edit your local machine’s SSH configuration file to enable the ServerAliveInterval feature.

  1. Open your local terminal application (the computer you are connecting from, not the server).
  2. Open your user-specific SSH configuration file in a text editor (create it if it doesn’t exist):
    nano ~/.ssh/config
  3. Add the following three lines to the file to apply the keep-alive rule to all hosts:
    Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
  4. Press Ctrl+O then Enter to save the file, and Ctrl+X to exit nano.
  5. (Optional) If you only want to apply this rule to a specific server, change Host * to Host your_server_ip.

By setting ServerAliveInterval 60, your local SSH client will automatically send an invisible packet to the Ubuntu server every 60 seconds if you are idle. This guarantees that data is constantly flowing through the tunnel, preventing aggressive firewalls from ever dropping your connection, no matter how long you leave the terminal window in the background.

Get the best tech tips delivered straight to your inbox.

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