Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Fix SSH “Connection Closed by Remote Host” Errors

Find the exact SSH failure phase, match it to server logs, and apply targeted fixes for MaxStartups, source bans, access rules, jump hosts, algorithm mismatches, host keys, and idle session drops.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Connection closed by remote host” means the SSH server (or an SSH gateway in front of it) actively terminated your connection. The last line in ssh -vvv tells you where to investigate: a closure at kex_exchange_identification occurs before authentication, while a drop after login points to session, forwarding, network, or keep-alive behavior. Capture the client debug output and the matching server log entry before changing configuration.

What the error means

SSH connections progress through distinct phases. Your client first establishes TCP, receives the server banner, negotiates a protocol and cryptographic algorithms, authenticates a user, starts a session, and may then open forwarding channels. “Connection closed by remote host” is a result, not a diagnosis: the remote endpoint chose to close the socket. The phase and the exact preceding message identify the cause.

Last useful client message Likely phase First place to look
ssh: connect to host ... port 22: Connection refused TCP connection Service listening state, firewall, security group, and port number
kex_exchange_identification: Connection closed by remote host Pre-authentication admission or key exchange MaxStartups, per-source limits, bans, access policy, gateway rules, and algorithm compatibility
no matching key exchange method, cipher, MAC, or host-key algorithm Protocol negotiation Client/server versions and enabled algorithm lists
Password or public-key exchange begins, then closes Authentication User policy, account state, keys, permissions, authentication limits, and server logs
Login succeeds, then the session freezes or drops Established session Keep-alives, NAT/VPN/load-balancer idle timers, network loss, and server session limits

A closure before authentication is not fixed by changing ServerAliveInterval; keep-alives operate after a session has been established. Conversely, increasing pre-authentication limits will not repair a connection that dies after an idle period.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

As an Amazon Associate I earn from qualifying purchases.

Collect evidence before changing SSH

  1. Run a verbose client test. Use ssh -vvv user@host and save the complete output. OpenSSH’s -v option increases diagnostic detail; three v flags normally expose the phase and reason that matters.
  2. Record the exact time and source address. Note the client’s public IP, destination address, port, username, and whether the attempt used a direct connection, ProxyJump, VPN, or another tunnel.
  3. Inspect the server log at the same time. Depending on the distribution and service name, check journalctl -u sshd, journalctl -u ssh, /var/log/auth.log, or /var/log/secure. Match timestamps and source IPs rather than relying on a generic error message.
  4. Classify the final phase. Decide whether the last event was TCP connection, banner/key exchange, authentication, session startup, forwarding, or an idle disconnect.
  5. Change one thing, then retest. Keep an existing console, out-of-band terminal, or second administrator session open before reloading the SSH service. A malformed configuration or an overly broad access rule can otherwise lock out every administrator.

Also record the running versions with ssh -V on the client and the server’s OpenSSH package or sshd -V output where supported. Directive availability and defaults can change between releases and distributions.

Compare the evidence when several causes seem possible

When more than one explanation fits, compare the same six facts instead of changing several settings at once:

  1. Failure phase: pre-authentication, negotiation, authentication, forwarding, or an established session.
  2. Exact debug text: “Exceeded MaxStartups,” an algorithm error, a host-key warning, or a silent close each points to a different class of control.
  3. Matching server entry: the daemon’s timestamp and source address are stronger evidence than the client’s generic final line.
  4. Scope: determine whether every client fails or only one public address, office NAT, CI runner, or VPN exit.
  5. Path: compare a direct connection with a ProxyJump or tunnel path when policy allows.
  6. Timing: an immediate close suggests admission or negotiation; a repeatable delay after login suggests an idle timer, keep-alive, or network-path problem.

This comparison prevents a common mistake: treating all connection closures as authentication failures. A source-specific pre-auth ban, for example, can look like a bad key from the client side, while a gateway forwarding refusal can look like a dead destination.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix pre-authentication closures

1. Check MaxStartups and connection bursts

MaxStartups limits simultaneous unauthenticated connections. New attempts can be dropped while existing clients are still in the login process or waiting for the login grace period to expire. OpenBSD documents the default random-drop form as 10:30:100: up to 10 unauthenticated connections are accepted without random dropping, the drop probability rises as the count increases, and connections are rejected at 100. The exact effective value on your host is authoritative.

Look for a server-log entry such as Exceeded MaxStartups. It commonly appears when automation, monitoring, configuration management, or a scan creates a burst of parallel SSH handshakes.

  • Measure how many unauthenticated connections are arriving and identify the job or source creating the burst.
  • Stop unnecessary parallel workers, add client-side pacing, or reduce simultaneous checks.
  • Restrict internet exposure with a firewall, private network, VPN, or source-based rate controls where appropriate.
  • Only after reducing pressure, consider a carefully sized MaxStartups increase that matches available CPU, memory, and expected authentication time.

Do not treat a larger limit as a universal cure. It can permit more expensive unauthenticated work and make a resource-exhaustion attack easier.

2. Investigate per-source limits, penalties, and bans

Modern OpenSSH configurations can apply controls in addition to the global startup limit. PerSourceMaxStartups restricts unauthenticated connections from one address. PerSourcePenalties can temporarily refuse a source after conditions such as invalid-user attempts or failed authentication. A single office NAT, CI runner, or VPN exit address can therefore be blocked even when other clients connect normally.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check every layer that can reject the source address:

  • Fail2Ban jails and their current ban list.
  • nftables or iptables rules on the host.
  • Cloud security groups, network ACLs, and provider firewalls.
  • An upstream intrusion-prevention system, load balancer, bastion, or VPN gateway.

The Fail2Ban OpenSSH filter includes patterns for pre-authentication Connection closed by remote host, connection resets, invalid users, authentication failures, and algorithm-negotiation failures. Confirm the address and the event that triggered the ban before removing it. Unban only the verified address and correct the underlying cause; disabling all protection first can expose the server while leaving the original problem unresolved.

3. Verify allow/deny policy and the effective configuration

Review AllowUsers, DenyUsers, AllowGroups, and DenyGroups in the complete configuration, including files included from the main configuration. A matching deny rule blocks login, and DenyUsers takes precedence over AllowUsers for the same user. Group membership, a username typo, or a Match block can make a policy look correct at first glance while still rejecting the request.

Validate syntax before reloading:

sshd -t

A successful check produces no error output and does not prove that the policy permits your particular user and address. To see the settings the daemon will actually use, print the effective configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sshd -T

When conditional rules may apply, supply the connection context:

sshd -T -C user=alice,addr=203.0.113.25,laddr=192.0.2.10,host=server.example

Replace the example values with the real username, client address, local address, and host. Compare the resulting values with the policy you intended, then reload the service through your distribution’s normal service manager while keeping your fallback session open.

4. Test jump hosts and forwarding gateways separately

With ProxyJump, a bastion, or a tunnel, there are at least two SSH paths: your client to the gateway and the gateway to the destination. The destination may be healthy while the gateway rejects the forwarding request. For example, an AllowTcpForwarding no policy prevents the gateway from carrying the connection even though ordinary logins to that gateway work.

  1. Connect to the gateway by itself and inspect its logs for your source address.
  2. Test the destination directly when network policy permits it.
  3. Compare the gateway’s forwarding settings with the destination’s SSH settings.
  4. Check both hosts’ logs for the same timestamp; a failure reported only on the gateway usually indicates a jump-path restriction.

Do not loosen forwarding globally just to make one route work. Scope an exception to the required account, destination, or gateway and document why it exists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5. Resolve protocol and algorithm mismatches

If verbose output reports that there is no matching key-exchange method, MAC, cipher, or host-key algorithm, the peers cannot agree on cryptographic parameters. This often appears when a modern client reaches an old endpoint or when a hardening change disabled the only algorithm a legacy device supports.

Compare supported lists on the client with:

ssh -Q kex
ssh -Q mac
ssh -Q cipher
ssh -Q key

Then compare those results with the server’s enabled algorithms and package version. Prefer upgrading the old endpoint or reconfiguring it to use currently supported algorithms. If a temporary compatibility option is unavoidable, put it in a narrowly scoped per-host client configuration entry, use it only for the named legacy host, and remove it after the endpoint is upgraded. Do not re-enable obsolete algorithms for every host.

6. Check host-key and identity issues safely

SSH stores server host keys in ~/.ssh/known_hosts. If a host’s identity changes, the client warns rather than silently trusting the new key. A rebuilt server, changed address, load-balanced name, or genuine interception attempt can produce this warning; deleting the file blindly removes useful protections.

  1. Verify the new host key through an independent channel, such as the system owner’s console or a trusted inventory.
  2. Confirm that the hostname and address are the intended server.
  3. After verification, remove only the stale entry:
ssh-keygen -R host.example

Retry the connection and validate the replacement fingerprint before accepting it. If the server reaches authentication but rejects the login, check the intended username, selected private-key file, agent identities, the account’s authorized_keys, and ownership and permission settings on the server.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

7. Distinguish authentication limits from admission limits

A server can accept the TCP connection and begin authentication yet still close the attempt because authentication policy is exhausted. OpenBSD documents a default MaxAuthTries value of 6; too many incorrect methods or keys in one attempt can reach that limit. An agent offering many identities may therefore fail even though the correct key is installed. Review the authentication-related log entry, confirm the intended username and identity, and avoid repeatedly retrying guesses that could trigger source penalties.

MaxSessions, documented with a default of 10, limits open shell, login, or subsystem sessions per network connection. It matters after transport establishment, especially when multiplexing or forwarding creates several channels. Do not raise it to solve a pre-authentication kex_exchange_identification closure; verify which phase actually failed.

Fix sessions that connect and then drop

A connection that succeeds and later disappears follows a different path from a kex_exchange_identification closure. First determine whether the drop happens after a fixed idle period, during active traffic, or when a network path changes.

Understand server keep-alives

ClientAliveInterval makes the server send encrypted probes over an established SSH connection. ClientAliveCountMax sets how many unanswered probes are tolerated. OpenBSD documents defaults of ClientAliveInterval 0 and ClientAliveCountMax 3. With an interval of 15 seconds and a count of 3, an unresponsive client can be disconnected after approximately 45 seconds; that timing applies only when those non-default settings are configured.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
ZPARIK 4 Pack Guest Checks Books for Servers Server Note Pads, Pink
  • Standard size: 4 pink server note pads, Each Book Comes with 50 bound order slips - that's 200 ticket sheets total! Check Pads Size 6.75 x 3.5 inch.
  • Convenient Work: These guest check books for servers have a tear-free dotted line that is easy to rip off. You can give as a customer copy or keep for record keeping. We've provided extra rows on the back for additional note taking.Perfect For Restaurants, Lounges, Hotels, Cafes, And Waiters To Use.
  • Record Important Information: These server note pads can record important information.Each ticket has a unique serial number printed at the top, dates, order details, number of guests, order amount, table numbers etc. They are lightweight, small and can fit most aprons. They can be used on-demand and can help decrease errors in orders, while improving work efficiency.
  • High Quality: Sturdy, Not Drop Powder, It's Thick, You Can Write On The Back And Front Easily.Their whole page printing has clear handwriting and a reasonable layout. On the customer retention part of each guest check, "THANK YOU" on the back to make customers feel appreciated.
  • Contact Us: We're confident that the quality of the server note pads will go beyond your expectation. If you experience an issue, contact us, we'll appreciate it to learn from your experience, and we'll make it better

Inspect the effective values with sshd -T. If the client is genuinely unreachable, increasing the count may delay detection but will not repair a broken route. Check firewall state, NAT expiration, VPN rekeying, Wi-Fi changes, and load-balancer idle timers as well.

Use a client keep-alive for an idle network path

For a path that drops only while idle, a client-side setting can send traffic often enough to keep intermediate devices from expiring the flow. A documented example is:

Host server.example
    ServerAliveInterval 120

Place this in the client’s SSH configuration for the affected host rather than applying it indiscriminately. A 120-second interval is an example, not a guarantee: choose a value below the shortest known NAT, firewall, VPN, or load-balancer idle timeout, and verify that the added traffic is acceptable. Keep-alives cannot solve a server that refuses the connection before authentication.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Configuration and recovery checklist

  • Keep a working console or second administrator session open.
  • Save ssh -vvv output, timestamp, username, destination, and source IP.
  • Match the attempt with journalctl -u sshd, journalctl -u ssh, /var/log/auth.log, or /var/log/secure.
  • Run sshd -t before reloading any edited configuration.
  • Use sshd -T, with -C context when needed, to inspect effective settings.
  • Check MaxStartups, PerSourceMaxStartups, penalties, Fail2Ban, host firewalls, cloud controls, and upstream IDS rules for pre-auth failures.
  • Review AllowUsers, DenyUsers, AllowGroups, and DenyGroups for the actual username and source address.
  • Separate gateway tests from destination tests when using ProxyJump or forwarding.
  • Compare algorithm support before adding any compatibility exception.
  • Verify changed host keys out of band before removing a specific known_hosts entry.
  • For post-login drops, inspect keep-alive values and network idle timers instead of raising pre-authentication limits.
  • After every single change, retry once and compare the new client and server evidence.

Version and platform differences

Service names, log locations, included configuration files, and available directives vary by operating system and package. Use the target host’s installed manual page and the output of sshd -T rather than assuming that a setting from another distribution applies unchanged.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

OpenSSH 10.4/10.4p1 was released on July 6, 2026. Its release notes include changes affecting connection limits, penalties, and keep-alive handling, so record the package version when comparing behavior across hosts. A configuration that worked on an older release may have different defaults or additional controls after an upgrade.

When to escalate

Escalate to the network or platform owner when the server log never sees the attempt, when only a gateway path fails, or when a cloud firewall, load balancer, or upstream IDS is the component closing the connection. Escalate to the system owner when the effective SSH configuration differs from the approved policy, when bans recur from a shared address, or when an algorithm exception would require weakening fleet-wide cryptographic settings.

The fastest resolution is usually a three-way match: the client’s last verbose line, the server’s log entry at the same time, and whether other source addresses or direct paths behave differently. That combination identifies whether you are dealing with admission pressure, a source-specific block, policy, negotiation, or an established-session network failure.

Frequently Asked Questions

Why does SSH say “connection closed by remote host” before I enter a password?

That is usually a pre-authentication closure. Check the server log for Exceeded MaxStartups, per-source limits, penalties, Fail2Ban or firewall bans, allow/deny rules, gateway restrictions, and algorithm negotiation errors. Run ssh -vvv and match its timestamp and source IP to the daemon log.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I fix kex_exchange_identification: Connection closed by remote host?

First determine whether the source is being refused or the server is overloaded. Inspect MaxStartups, PerSourceMaxStartups, penalties, and security tools for the client’s public address. If the log shows an algorithm mismatch, compare ssh -Q output and upgrade or narrowly scope a compatibility setting. Do not start with keep-alives; they apply only after login.

Why does SSH work from one network but not another?

A difference by source address points to a per-source limit, temporary penalty, Fail2Ban entry, host firewall, cloud security group, upstream IDS, or a gateway policy. Compare the public addresses and server log entries, then remove only a verified ban and correct the event that caused it.

Why does my SSH session drop after I enter the password?

Determine whether authentication succeeds and whether the drop is immediate or follows an idle period. Check account policy, keys, permissions, MaxAuthTries, and MaxSessions for authentication or session failures. For idle drops, inspect ClientAliveInterval, ClientAliveCountMax, NAT, VPN, firewall, and load-balancer timers; a client-side ServerAliveInterval 120 may keep an idle path active.

Should I increase MaxStartups to stop the error?

Only when logs and connection measurements show a legitimate unauthenticated burst. Reduce parallel jobs and restrict exposure first, then size the limit for the host’s resources. Raising it blindly allows more unauthenticated work and can increase resource-exhaustion risk.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is it safe to delete known_hosts when SSH closes?

No. A changed host key can indicate a rebuild, address change, load balancer, or interception. Verify the fingerprint through an independent channel, then remove only the specific entry with ssh-keygen -R host and validate the replacement key.

The Bottom Line

Start with ssh -vvv, the exact failure phase, and a matching server log. Pre-authentication closures usually involve MaxStartups, source limits or bans, policy, gateways, or algorithm negotiation; post-login drops require session and network-timer checks. Validate with sshd -t, inspect effective settings with sshd -T, make one narrowly scoped change, and keep a recovery session open.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.