CH-J Toolsserver management over SSH
Menu
All guides and articles →

Why SSH disconnects after a few minutes and how to prevent it

Distinguish between lost network session, idle shell, and server limit. Set keepalive based on the cause and protect long-running tasks from connection dropout.

First, determine what actually got disconnected

A disconnected SSH can look the same for a wide variety of reasons. Sometimes the network transport is interrupted, other times the remote shell terminates and the network itself is working. On a closed laptop, the client process may stop running; on a mobile connection, a network change may invalidate the original TCP connection. Therefore, a proper fix starts with an accurate report, time, and circumstances, not by adding random settings to the server.

Note whether the session ended while typing, when idle, after the same amount of time since logging in, or when changing Wi-Fi. If multiple users are disconnecting at the same time, compare their network path and server. If a single laptop in the same office is failing, the problem could be with its sleep, VPN, or security software. Testing from the same device over a different enabled network will help narrow down the cause.

  • Broken pipe or Connection reset are manifestations of interrupted communication; they do not themselves identify the device that caused the interruption.
  • Connection closed can accompany both a normal shell exit and a server policy; the previous context is decisive.
  • ServerAlive and ClientAlive check whether the other party is responding. They do not reestablish a dead TCP connection.
  • ConnectTimeout addresses connection establishment, not the length of the logged-in session.

Capture one reproducible case

Run a single test session with a detailed log on the OpenSSH client. Do not create dozens of concurrent connections: service blocking or limits will complicate diagnostics. When recording, distinguish between client and server time, including time zone. The log may contain server names, accounts, and local paths, so anonymize it before sharing it with others.

ssh -vvv -E ssh-odpojeni.log spravce@server.example
ssh -G spravce@server.example | grep -E "^(hostname|port|proxyjump|serveraliveinterval|serveralivecountmax|tcpkeepalive) "

In the second output, you see the evaluated client configuration, not a guarantee that the same files are being retrieved by another application. Use the same account, target port, and bastion (if any) for the test as you normally would. If the session disconnects after inactivity, note the last write time and the actual time to error. When an active transfer is interrupted, the pattern is different, and simply maintaining an idle session is probably not enough.

Request the corresponding SSH events on the server at the given time. Ubuntu and Debian usually use ssh.service, other distributions use sshd.service. A missing record on the server could mean that the client has not reached it yet, but it could also mean a different logging backend. Therefore, verify that you see at least the event of its creation for the same test login.

sudo journalctl -u ssh.service --since "-30 min" --no-pager
uptime
who

Set up session maintenance on one client first

If the connection is regularly dropping out of service when idle, you can try a protocol keepalive. For the OpenSSH client, the following example sends a query after 30 seconds of no data received and closes the session after several unanswered queries. Set the interval and count based on your actual connection. On an unstable mobile network, too strict values may cause more frequent terminations.

ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  spravce@server.example

# Cílené nastavení v ~/.ssh/config:
Host muj-server
    HostName server.example
    User spravce
    ServerAliveInterval 30
    ServerAliveCountMax 3

Compare the test to the original state on the same network. If instead of five minutes, the idle session lasts significantly longer, this is a reason to suspect a network timeout. It does not say whether the decision was made by the home NAT, corporate firewall or VPN. If the change does not help, do not shorten the interval indefinitely; continue checking the server, shell and sleep.

TCPKeepAlive uses a different mechanism and its timing depends on the operating system. It should not be confused with queries at the encrypted SSH protocol level. Adding ServerAliveInterval also does not solve the client sleep: a process that is not running cannot send a query. Therefore, distinguish display power saving mode from real computer sleep.

Check server limits and shell timings

The ClientAliveInterval setting on the server is used to verify client responses. It is not a general rule of thumb to "log out a user who is not typing." The client can respond to log messages even if the administrator is away for a long time. Interactive shell inactivity can be handled separately, for example, by the TMOUT variable in Bash or by corporate policy. These mechanisms may overlap.

# V postiženém Bashi:
printf "TMOUT=%s\n" "${TMOUT-unset}"

# Na serveru zkontrolujte účinné nastavení pro skutečný účet a adresu:
sudo /usr/sbin/sshd -T -C user=spravce,addr=203.0.113.10,host=klient.example \
  | grep -E "^(clientaliveinterval|clientalivecountmax|channeltimeout|unusedconnectiontimeout) "

Newer versions of OpenSSH may have ChannelTimeout for inactive channels and UnusedConnectionTimeout for connections without channels. Older versions do not support these options. Also use your local man sshd_config and package version when checking the documentation; copying a new directive into an older daemon may cause an invalid configuration. Do not change the management limit intentionally without consulting your security policy administrator.

If the server policy change is justified, back up the modified file, do sshd -t and reload the correct service. Verify the result in a new connection. Leave the original session open, as the new limits and new Match blocks may not affect it in the same way. So success in the original terminal is not a sufficient test.

When NAT, VPN, IPv6 or bastion decides

There can be several places in the SSH path that keep track of the connection state. VPNs can re-establish tunnels, and NAT can forget mappings when idle. Switching between Wi-Fi and mobile data can change the source address; a regular SSH session will not automatically move to a new connection. Check to see if the outage coincides with a VPN re-establishment, roaming, or address change.

ssh -4 -o ServerAliveInterval=30 spravce@server.example
ssh -6 -o ServerAliveInterval=30 spravce@server.example

These two tests compare different network paths. IPv4 success is not proof of IPv6 success, and vice versa. If large outputs or transfers are stuck while small commands work, also check the MTU and larger packet transfer. Do not disable the firewall or ICMPv6 across the board. You need to document the specific failure to fix, not just change the address family and stop tracking the original problem.

There is a connection to the bastion via ProxyJump and a proxy connection to the target. Diagnose each leg separately. The client settings for the target host may not apply to the bastion helper process. Therefore, in the OpenSSH configuration, adjust the targeted Host block for the bastion as well, if the problem is with it. Do not enable agent forwarding as an attempt to fix the timeout; this is a different function with different consequences.

Separate long tasks from the terminal's life

Even a well-established connection will sometimes end. For long compilations, transfers, or administrative operations, think about what happens after you close the terminal. For interactive work, tmux can help: the remote session runs on the server and you can reconnect to it. It is not a backup of the server, and its session will not survive a reboot of the machine or the termination of the relevant processes.

# Pokud je tmux na serveru nainstalován:
tmux new -s sprava
# Odpojení od tmux: Ctrl-b a poté d
# Po novém přihlášení:
tmux attach -t sprava

For long-running services, use proper service management with status and logs. Running a command with an ampersand does not resolve its input, output, permissions, or crash recovery. For a risky task, decide before starting how you will find out the result and whether it can continue without an administrator connected. For database migrations, losing visibility into state can be worse than disconnecting.

In CH-J Tools, verify the server identity, account, and job status after reconnecting. Do not automatically retry a command that may have succeeded before disconnecting. First, check its target status or output log. This is important for commands that create users, change database schema, or overwrite files.

Verifying the repair and returning to the original settings

Judge the fix based on the original scenario. If the session previously timed out after five minutes of no writing, observe the new attempt for at least significantly longer than five minutes. Then test for normal work, traffic, and approved VPN access. Don't consider the problem resolved just because the uptime command passed once. A short test won't test the timeout.

  • Record the cause, the changed file or client setting, and the test duration.
  • Eliminate test intervals that are too short if they have no measurable benefit.
  • Leave legitimate safety limits and set longer work to respect them.
  • If the cause remains unclear, keep the exact times and anonymized log ends from both sides.

If the change did not help, revert the specific diagnostic modification and keep the collected evidence. The goal is not to have as many keepalive options in the configuration as possible. The goal is to document what ended the session and ensure that the administrator does not lose work or information about the state of the server after an unexpected outage.

Frequently asked questions

Will ServerAliveInterval prevent the laptop from going to sleep?

No. Sending queries requires a running client and a working network. A new connection may be required after a true sleep or network change.

Is ClientAliveInterval logging out inactive users?

Not directly. It detects client responses at the protocol level. Shell or channel inactivity is handled by other mechanisms.

Will tmux survive a server restart?

A regular tmux session will not survive a machine reboot. It protects interactive work when the client disconnects, not when the server process dies.

Should I rerun the last command after an outage?

Check the status first. The command may have finished running even after you stopped seeing its output.

Detailed documentation

OpenSSH: client and ServerAlive setup →

OpenSSH: server limits and ClientAlive →

GNU Bash: TMOUT variable →

tmux: introduction and session management →

Biometric unlock and security →

All tutorials by category →