SSH from Windows system picking up wrong public key from known hosts file

Abstract: Resolve SSH connection failures caused by cached host key mismatches when connecting to servers with dynamic IPs or behind NAT.

Created: 2026-09-03 by

SSH on Windows often connects to the wrong server identity because it caches host keys in %USERPROFILE%\.ssh\known_hosts. This happens when multiple machines share an IP address, such as behind NAT or in dynamic cloud environments. The client trusts the cached key instead of verifying the current server's actual fingerprint, leading to connection failures or security warnings.

Understanding the Known Hosts Mechanism

When you first connect to a remote Linux server via SSH from a Windows machine using tools like OpenSSH Client, PuTTY, or MobaXterm, the system prompts you to accept the server's public key. If you agree, this key is stored in your local known hosts file. On Windows, this file is typically located at C:\Users\\.ssh\known_hosts for native OpenSSH clients. The purpose of this file is security. It ensures that you are connecting to the same server every time and not falling victim to a Man-in-the-Middle (MitM) attack. However, if the server's IP address changes but its hostname remains the same, or if multiple servers are behind a single IP (common in corporate networks or cloud instances), the cached key becomes invalid. The SSH client sees a mismatch between the new server's key and the old one stored in the file, causing it to reject the connection immediately with a "REMOTE HOST IDENTIFICATION HAS CHANGED" error.

Why This Happens Frequently on Windows

Windows users often face this issue more frequently due to several factors:
  • Dynamic IPs: Cloud providers often assign ephemeral IPs. If you access a server by hostname, the DNS might resolve to a different IP than before, but the known_hosts file still holds the old key.
  • NAT and Load Balancers: Multiple backend servers may share a single public IP. When the load balancer routes your connection to a different backend, the server key changes, triggering the warning.
  • Multiple Users/Profiles: If you switch Windows user accounts, each has its own .ssh directory. Confusion can arise if keys are shared or mismanaged across profiles.
For more details on managing SSH connections, you might find Troubleshooting 'Remote side unexpectedly closed network connection' Error in MobaXterm helpful, as MobaXterm also manages its own host key cache separately from the native Windows OpenSSH client.

Solving the Wrong Key Issue

To fix this, you must remove the outdated or incorrect entry from your known hosts file. Follow these steps carefully to ensure you do not delete the wrong entry.

Step 1: Identify the Problematic Entry

First, determine which entry is causing the conflict. You can list all entries in the known hosts file using the following command in PowerShell or Command Prompt:
type %USERPROFILE%\.ssh\known_hosts
Look for the hostname or IP address of the server you are trying to reach. Note the line number or the exact content of the line. Be cautious, as a single line can contain multiple keys separated by commas if you have connected to the same host via different methods.

Step 2: Remove the Incorrect Key

You can remove the specific entry using the ssh-keygen utility, which is safer than manually editing the file. Use the -R flag followed by the hostname or IP:
ssh-keygen -R [hostname_or_ip]
If the server uses a non-standard port, include the port in square brackets:
ssh-keygen -R [hostname]:port
This command will delete the specified entry from the known_hosts file. If you prefer manual editing, open %USERPROFILE%\.ssh\known_hosts in a text editor like Notepad++, find the line corresponding to the problematic server, and delete it entirely. Save the file after removal.

Step 3: Re-establish the Connection

Once the old key is removed, attempt to SSH into the server again:
ssh username@hostname
The client will now detect that there is no cached key for this host. It will display the server's current public key fingerprint and ask if you want to continue connecting. Verify the fingerprint against the server administrator or the official documentation to ensure authenticity. Type yes to accept and store the new key.

Preventing Future Conflicts

To avoid this issue recurring, consider using SSH config files to manage multiple identities for the same IP address. Create or edit %USERPROFILE%\.ssh\config and define specific settings for each host. For example:
Host myserver1
    HostName 192.168.1.100
    User admin
    IdentityFile ~/.ssh/id_rsa_server1

Host myserver2
    HostName 192.168.1.100
    User devops
    IdentityFile ~/.ssh/id_rsa_server2
By using distinct aliases (myserver1, myserver2) for the same IP, SSH treats them as separate entities, maintaining separate key caches. This is particularly useful in environments where multiple services run on the same machine but require different authentication contexts. Additionally, always verify fingerprints when connecting to new or changed hosts. Never blindly accept unknown keys. If you frequently encounter this issue due to dynamic infrastructure, consider implementing automated key management solutions or using certificate-based authentication instead of traditional key pairs. For users experiencing broader connectivity issues alongside key problems, reviewing Troubleshooting kex_exchange_identification Error in Linux SSH Connection can provide insights into other common SSH handshake failures that might compound with host key mismatches.

Frequently Asked Questions

How do I clear all known hosts entries?

You can delete the entire known_hosts file by running del %USERPROFILE%\.ssh\known_hosts in the command prompt. However, this removes trust for all previously connected servers, requiring you to re-verify each one individually upon next login.

Can I disable the known hosts check?

While you can set StrictHostKeyChecking=no in your SSH config, this is strongly discouraged for security reasons. It makes you vulnerable to Man-in-the-Middle attacks by automatically accepting any new server key without verification.

Why does PuTTY show a different key than Windows OpenSSH?

PuTTY stores its host keys in the Windows Registry under HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys, while native Windows OpenSSH uses the known_hosts file. They do not share cache data, so you may need to clear keys in both locations if switching clients.

What if I cannot identify the correct line in known_hosts?

If the file is large, use grep hostname %USERPROFILE%\.ssh\known_hosts to filter only the relevant lines. If you are unsure which key belongs to which server, compare the fingerprints shown in the error message with the expected fingerprints provided by your system administrator.

Does changing the SSH port affect the known hosts file?

No, the standard known_hosts file does not distinguish by port unless you explicitly specify the port in the hostname syntax (e.g., [host]:port). Using the -R flag with just the hostname will remove all entries for that hostname regardless of the port used.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More