How to Stop SSH Sessions from Disconnecting Due to Inactivity in Linux

Why Do SSH Sessions Disconnect?

When you connect to a remote Linux server via SSH, the connection may suddenly drop or freeze if you leave the terminal idle for too long. This happens because firewalls, routers, or the server itself automatically terminate inactive TCP connections to save resources.

To prevent this “broken pipe” or “connection reset by peer” error, you can configure your SSH client to send periodic “KeepAlive” packets to the server. These tiny, invisible packets trick the network into thinking the connection is still active.

How to Enable KeepAlive for the SSH Client

You can configure your local Linux or macOS machine to automatically send KeepAlive packets for all outgoing SSH connections.

  1. Open your local terminal.
  2. Edit the SSH client configuration file using a text editor like nano. You will usually need root privileges. Run the following command:
sudo nano /etc/ssh/ssh_config
  1. Scroll to the bottom of the file and add the following two lines:
ServerAliveInterval 60
ServerAliveCountMax 3

What these settings do:

  • ServerAliveInterval 60: Tells your SSH client to send a null packet to the server every 60 seconds of inactivity.
  • ServerAliveCountMax 3: Tells the client to drop the connection if the server fails to respond to 3 consecutive KeepAlive packets.
  1. Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

These changes take effect immediately for any new SSH connections you initiate.

How to Enable KeepAlive on the SSH Server

Alternatively, if you manage the remote server, you can configure the server to send KeepAlive packets to connected clients. This prevents connections from dropping regardless of the client’s configuration.

  1. Log into your remote server.
  2. Edit the SSH daemon configuration file:
sudo nano /etc/ssh/sshd_config
  1. Find or add the following lines:
ClientAliveInterval 60
ClientAliveCountMax 3
  1. Save the file and exit the editor.
  2. Restart the SSH service for the changes to take effect:
sudo systemctl restart ssh

By enabling KeepAlive packets on either the client or the server, your SSH sessions will remain stable and open, even during long periods of inactivity.

Get the best tech tips delivered straight to your inbox.

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