Keeping Connection Alive
SSH connections can be terminated by network infrastructure (firewalls, NAT devices, load balancers) or the remote server when there's no activity for an extended period. If you're not actively using the connection for a long time, you need to send keepalive messages to prevent these timeouts.
Why You Need Keepalives
When your SSH connection is idle (not executing commands or transferring files), it can be terminated:
Network devices may drop idle connections - Firewalls and NAT gateways often have idle timeout policies (typically 5-15 minutes)
SSH servers may disconnect idle sessions - Many servers have
ClientAliveIntervalconfigured to terminate inactive connectionsLong-running operations may appear stalled - Without activity, monitoring systems may flag the connection as dead
Keepalive messages solve this by sending periodic SSH protocol messages that keep the connection active.
Configuring and Sending Keepalives
Configure keepalives after connecting and send them periodically when you're not actively using the connection:
Parameters
wantReply:
false- Send keepalive without expecting a reply (recommended, lower overhead)true- Require the server to acknowledge keepalives (useful for detecting broken connections)
interval:
The time between keepalive messages
Typical values: 30-60 seconds
Must be less than the smallest timeout in your network path
Detecting Connection Failures
When wantReply: true, the server must acknowledge keepalives. This helps detect broken connections:
Best Practices
Choose appropriate intervals:
30-60 seconds for typical use cases
Shorter intervals (15-30s) for restrictive networks
Avoid very short intervals (<15s) - they waste bandwidth
Use wantReply: false by default:
Lower overhead
Sufficient for most keepalive scenarios
Only use
wantReply: truewhen actively monitoring connection health
Only send keepalives when idle:
No need to send keepalives while actively executing commands or transferring files
SSH activity naturally keeps the connection alive
Coordinate with server timeouts:
Set keepalive interval lower than server's
ClientAliveIntervalCheck network infrastructure timeouts (firewalls, load balancers)
See Also
SshSession.ConfigureKeepAlive()(SshSession.cs:325) - Configure keepalive settingsSshSession.SendKeepAlive()(SshSession.cs:300) - Manually send a keepalive messageSession Timeouts - Understanding timeouts vs keepalives
Session Lifecycle - When to send keepalives
Authentication - Authenticate before using keepalives
Error Handling - Handle keepalive errors