SSH Credentials Added Twice: Unable to Remote Connect via SSH on Ubuntu

Abstract: Resolve SSH connection failures caused by duplicate host keys in known_hosts using ssh-keygen -R.

Created: 2026-10-20 by

SSH credentials appearing twice in ~/.ssh/known_hosts causes connection failures because the SSH client detects a host key mismatch when multiple entries exist for the same IP address. This issue typically arises from re-imaging servers, changing network configurations, or connecting to different machines with identical IPs. The solution involves cleaning the duplicate entries using the ssh-keygen -R command to restore secure connectivity.

Understanding the Known Hosts Mechanism

When you connect to an SSH server for the first time, your local machine prompts you to verify the server's fingerprint. Upon acceptance, this public key is stored in the ~/.ssh/known_hosts file. This mechanism prevents Man-in-the-Middle (MitM) attacks by ensuring that the server you are connecting to has not changed its identity unexpectedly. The SSH client reads this file sequentially. If it finds more than one entry for the same hostname or IP address, it cannot determine which key is the correct one. Consequently, it aborts the connection and displays an error message indicating that the host key for the site has changed or that there are conflicting entries. This behavior is a security feature, not a bug, designed to protect users from connecting to potentially compromised hosts.

Common Causes of Duplicate Entries

Several scenarios can lead to duplicate SSH credentials being added to your local configuration. Identifying the root cause helps prevent recurrence after you fix the immediate issue.
  • Server Re-imaging: If you reinstall an operating system on a physical server without changing its IP address, the new installation generates a different SSH host key. Your local machine still holds the old key, resulting in two conflicting entries.
  • NAT or DHCP Conflicts: In home lab environments or virtualized setups, dynamic IP assignment may give the same IP address to different virtual machines. Connecting to the IP twice effectively adds keys for two different hosts under the same identifier.
  • Manual Editing Errors: Accidentally copying and pasting lines into the known_hosts file or merging files from different systems can introduce duplicates manually.
For more context on related SSH connectivity issues, such as hangs in VirtualBox environments, you might find Troubleshooting SSH Hangs on Kubuntu 24.04 and Ubuntu 24.01 in VirtualBox useful. Additionally, understanding permission issues can help if your cleanup commands fail due to file access rights, as discussed in SSH Permission Denied on Port 22: Home Lab Server Issue.

Identifying the Problem in Terminal Output

When the issue occurs, the terminal output will explicitly mention the conflict. You might see an error similar to:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
It is possible that someone is doing something nasty!
...
Offending ECDSA key in /home/user/.ssh/known_hosts:5
Offending ECDSA key in /home/user/.ssh/known_hosts:12
Password authentication is disabled or not configured.
Note the line numbers provided (e.g., :5 and :12). These indicate exactly where the duplicate keys reside in your file.

Solving the Duplicate Key Issue

The most efficient way to resolve this is to remove the offending entries automatically rather than editing the file manually. Manual editing risks introducing syntax errors or leaving behind partial lines that could still cause issues. Use the ssh-keygen utility with the -R flag. This flag tells SSH to remove all keys associated with the specified hostname or IP address.

Step-by-Step Removal Process

  1. Identify the Hostname or IP: Determine the exact string used in your SSH command. For example, if you ran ssh [email protected], the target is 192.168.1.50.
  2. Run the Removal Command: Execute the following command in your terminal:
    ssh-keygen -R 192.168.1.50
    If you use a hostname like myserver.local, replace the IP with that hostname.
  3. Verify the File: You can check the status of the file by viewing its contents. Use cat ~/.ssh/known_hosts to ensure the duplicate lines are gone. The command output usually confirms how many keys were removed.
  4. Reconnect: Attempt to SSH into the server again. You will be prompted to accept the new host key. Type yes to add the current, correct key to your list.
If you have multiple duplicates or are unsure which ones are valid, you can remove all entries for a specific host by running the command again. SSH only stores one active key per host; any subsequent connections will update this single entry.

Handling Persistent Issues

In rare cases, the ssh-keygen -R command might not remove the entry if the file has incorrect permissions. Ensure that the known_hosts file is owned by your user and has read/write permissions for the owner only. You can reset permissions using:
chmod 600 ~/.ssh/known_hosts
This ensures that only you can read or modify the file, which is a standard security practice for SSH configurations. If you continue to experience connection problems, consider checking for broader network or service issues, such as those described in Troubleshooting SSH WSL Machine: Can't Connect to Localhost, particularly if you are working within a Windows Subsystem for Linux environment.

Preventing Future Conflicts

To minimize the risk of encountering duplicate keys again, adopt consistent naming conventions. Instead of relying solely on IP addresses, use static hostnames in your ~/.ssh/config file. This allows you to map specific IPs to unique aliases, making it easier to manage multiple servers that might share temporary IP ranges. Additionally, regularly audit your known_hosts file if you frequently rebuild infrastructure. Automated scripts can compare expected fingerprints against stored keys to alert you before a connection attempt fails.

Frequently Asked Questions

What does "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED" mean?

This warning indicates that the SSH server at the specified IP address has presented a different cryptographic key than what is stored in your local known_hosts file. It is a security measure to prevent Man-in-the-Middle attacks, suggesting either a legitimate server change or a potential security breach.

Can I edit the known_hosts file manually instead of using ssh-keygen?

While you can manually edit the file using a text editor like nano or vim, it is error-prone. Deleting specific lines requires knowing the exact line number, and accidental deletion of other entries can break connections to other servers. Using ssh-keygen -R is safer and more precise.

Why do I still get the error after removing the key?

If the error persists, you may have connected to a different server that now occupies the same IP address, or you have another stale entry for a different hostname resolving to that IP. Verify the server's actual fingerprint with its administrator and ensure you are removing the correct identifier from your local configuration.

Is it safe to ignore the warning and type yes?

No, never ignore this warning without verifying the server's identity through a separate channel. Ignoring it exposes you to MitM attacks where an attacker intercepts your connection. Always confirm the new fingerprint matches the official documentation or a trusted source before accepting it.

How do I check my current SSH version and config settings?

You can check your SSH client version by running ssh -V. To view detailed configuration options during a connection attempt, use ssh -v user@host or ssh -vvv for verbose debugging. This output shows exactly which keys are being loaded and where conflicts arise.

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