Linux

SSH Host Key Changed? Verify Server Identity Before Updating known_hosts

The Back Room Tech Staff · Edited by Aseem Kishore
15 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

An SSH host key changed warning means the server’s key conflicts with saved trust in OpenSSH. A rebuild can cause this, but it doesn’t prove the new server’s identity.

Save the warning, check the endpoint, and compare its fingerprint through a trusted, separate channel. Then back up the trust file and update only the confirmed stale record.

Prerequisites

This runbook covers an existing OpenSSH client on Linux, including Ubuntu and Debian systems. It manages client trust; it doesn’t create or rotate server keys.

You’ll need:

  • Existing ssh and ssh-keygen commands.
  • Read access to the trust file named in the warning.
  • An authenticated server console, established out-of-band access, or a trusted administrator with verified records.
  • Approval to update the affected trust record after verification.
  • A place to keep the warning, backup, and change or incident notes.

You don’t need extra hardware if trusted console access already exists. For a Raspberry Pi or NAS appliance, check the recovery path before changing client trust.

The commands below use documentation-only destinations: server.example.com and 203.0.113.10. Use your actual endpoint and username.

The option reference is the OpenBSD 8.0 ssh-keygen manual. That version isn’t a minimum Linux requirement. Check your installed manual for local option details.

Quick Diagnosis: SSH Host Key Changed

The warning proves that saved trust conflicts with the key shown during this connection. It doesn’t prove who controls that key. OpenSSH checks host identity before normal access continues; see the ssh manual.

Start with the symptom that matches your case:

Symptom or scenarioLikely causeSafe next action
Warning follows an approved rebuildThe replacement has a different host keyVerify its fingerprint independently
Warning appears without planned maintenanceWrong endpoint, unexpected change, or interceptionSave the evidence and investigate
Hostname isn’t visible in known_hostsHashed hostname or another stored identitySearch with ssh-keygen -F
Lookup finds nothingWrong file, hostname, address, or portMatch the warning’s exact identity and path
Several records matchMultiple saved keys for the identityReview every match before removal
Warning persists after an updateAnother file, account, or identity is involvedInspect the new warning
Automated job fails after a rebuildIts controlled trust file still has stale trustUpdate through the automation owner’s process
Different connections show different keysFailover or backend identity mismatchEscalate for a verified service identity policy

Follow the five steps below in order. If the independent fingerprint is unavailable or doesn’t match, stop before changing trust.

Five Steps to Resolve the Warning Safely

1. Problem: SSH reports that remote host identification has changed

Symptoms

  • The terminal reports “WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!”
  • The warning names an offending key and a known_hosts line.
  • The connection ends with “Host key verification failed.”

Cause

The endpoint presented a key that conflicts with a saved record. A rebuild, replacement machine, wrong destination, or intercepted connection could cause this.

An approved maintenance event helps explain the change. It doesn’t prove the key belongs to the intended server.

Solution

Stop the connection and save the full warning before editing anything. Copy the terminal output into the change or incident record.

Record these details:

EvidenceWhat to preserve
Original commandInclude aliases, options, username, and destination
TimeRecord the timestamp and time zone
EndpointEntered hostname or IP address
PortEffective SSH port, usually 22 unless configured otherwise
Presented identityKey type and complete fingerprint
Affected fileExact trust-file path from the warning
Offending recordLine number and stored key type
ContextRebuild, restore, replacement, failover, or unexplained change

Don’t assume the stored key and the presented key have the same type. Record both as shown.

You can get a UTC timestamp with:

date -u '+%Y-%m-%dT%H:%M:%SZ'

Expected result: a timestamp ending in Z, which means UTC. Keep the original connection time separately if you run this command later.

Controlled changed-host-key warning for server.example.com showing the presented key type and complete fingerprint, affected known_hosts path, and offending line number before any edits

Verification

Check that someone reading the record could identify the exact attempted connection and affected file. A cropped warning without its fingerprint or file path leaves gaps.

2. Problem: A rebuild, address change, or connection alias may explain the warning

Symptoms

  • The warning starts after maintenance.
  • A hostname points to a replacement machine.
  • An alias reaches a different endpoint than expected.
  • Port 2222 behaves differently from port 22.

Cause

Hostnames, addresses, and ports can lead to different machines or SSH services. Restores and failovers can also change which host key appears.

A correct hostname alone doesn’t settle the question. Check which machine is behind it.

Solution

Review the original command and the approved change record. Confirm:

  • The intended server and its current owner.
  • Any approved rebuild, replacement, restore, failover, or host-key change.
  • The expected hostname and address.
  • The SSH port.
  • Whether an alias or client configuration changes the destination.
  • Whether a jump host or automated wrapper affects the connection.

Compare these two examples:

ssh user@server.example.com
ssh -p 2222 user@server.example.com

The -p option selects the remote port. These commands can reach different services with different identities. Their output depends on the service reached; save any host-key warning.

Read the relevant entries in $HOME/.ssh/config and /etc/ssh/ssh_config. For the effective client configuration without making a connection, use the upstream-documented option:

ssh -G user@server.example.com

Preserve the original alias and command-line options when adapting that example. Review hostname, port, hostkeyalias, userknownhostsfile and globalknownhostsfile in its output. If you use an alias, inspect its settings; the entered name may not be the trust identity.

If the warning names 203.0.113.10, check that address specifically. Don’t clear both hostname and address records as a precaution.

Verification

You should be able to name the intended machine, hostname or address, effective port, and relevant change reference.

If those details don’t agree, fix the destination problem first. If they agree, check the fingerprint through an independent source.

3. Problem: The replacement fingerprint is unverified or doesn’t match

Symptoms

  • The warning shows an unfamiliar fingerprint.
  • An administrator supplies a different fingerprint.
  • Someone suggests trusting a key collected from the same network connection.
  • The only available check would use the disputed SSH session.

Cause

A fingerprint identifies a public key. It helps prove identity when it comes from a trusted source.

Different host-key types also produce different fingerprints. Comparing an Ed25519 fingerprint with an RSA fingerprint won’t verify either key.

Solution

Get the intended endpoint’s fingerprint through one of these independent channels:

Verification channelWhat makes it suitable
Authenticated server consoleAccess is established separately from the disputed SSH connection
Established out-of-band managementThe management endpoint and access path are already trusted
Trusted administratorTheir identity and information source are confirmed
Trusted inventoryThe record’s source is confirmed, and it applies to this endpoint and key type

At a trusted Linux server console, an administrator can inspect the standard Ed25519 host public key:

# -l displays the fingerprint; -f selects the public-key file.
ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub

For an RSA host public key:

ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub

These commands inspect public keys without changing them. The paths are standard examples; check the public-key path the server actually uses.

Expected result: fingerprint output that identifies the public key and its type. Compare that output with the client warning:

  • Confirm the same endpoint and port.
  • Confirm the same key type.
  • Compare the complete fingerprint.
  • Ensure both fingerprints use the same format.

Don’t compare only the start or end of a fingerprint. Ask the administrator for a matching format if they differ.

Trusted independent server console showing ssh-keygen fingerprint output for the actual deployed host public key, with the key type and complete fingerprint visible

Why ssh-keyscan isn’t sufficient

ssh-keyscan can collect keys offered over a network connection. That alone doesn’t prove the server’s identity.

If the connection reaches an impersonator, the collected key can belong to that impersonator. Treat it as untrusted until its fingerprint matches a separate, trusted source.

Verification

Proceed only when the presented key type and complete fingerprint match the independently verified value.

Stop if you can’t verify the fingerprint or the values disagree. Keep saved trust unchanged and escalate to the system owner or security process. An expected rebuild doesn’t override a mismatch.

4. Problem: The stale entry is hidden, duplicated, or stored under another identity

Symptoms

  • A text search doesn’t find the hostname.
  • Records start with unreadable hashed values.
  • ssh-keygen -F returns several matches.
  • A hostname lookup finds nothing, but the warning names a nondefault port.
  • The warning points to a different trust file.

Cause

OpenSSH can store hashed hostnames. Trust records also depend on the identity used for lookup, including nondefault ports.

A hostname, an IP address, and a bracketed host-and-port value are separate lookup identities. Another file may hold the conflicting record.

Solution: inspect first

Use the exact file named in the warning. Confirm it exists and is readable before the examples below. If the default file is absent, a configured path differs, or permissions prevent reading it, stop and resolve that condition through the file owner; do not create an empty replacement or relax permissions. Check every configured trust file when more than one applies. For the default per-user file and a normal hostname:

# -F finds matching records, including hashed hostnames.
# -f selects the affected trust file.
ssh-keygen -F 'server.example.com' -f "$HOME/.ssh/known_hosts"

For port 2222:

ssh-keygen -F '[server.example.com]:2222' -f "$HOME/.ssh/known_hosts"

Expected result: matching records and their line references. If there’s no match, recheck the identity and file before removing anything.

The quotes keep the bracketed identity intact in the shell. Nondefault-port records use the form [hostname]:port.

If the warning names the IP address, inspect it separately:

ssh-keygen -F '203.0.113.10' -f "$HOME/.ssh/known_hosts"

For that address on port 2222:

ssh-keygen -F '[203.0.113.10]:2222' -f "$HOME/.ssh/known_hosts"

These lookups should show any matches for the exact address, port, and file. Don’t use address lookups as a reason to remove extra records. Confirm the scope for each affected identity.

Exact ssh-keygen -F lookup for '[server.example.com]:2222' against the affected known_hosts file, showing all matching records for review

Preserve a separate backup

After verification and before editing, back up the affected file. This Linux example creates a separate directory and copies the default per-user trust file:

# mktemp creates a separate backup directory.
# cp -p preserves the file's permissions and timestamps.
backup_dir="$(mktemp -d "$HOME/.ssh/known_hosts-review.XXXXXXXX")" &&
cp -p -- "$HOME/.ssh/known_hosts" "$backup_dir/known_hosts" &&
printf 'Backup saved to: %s/known_hosts\n' "$backup_dir"

Expected result: a printed backup path. If the command fails or prints no success message, fix the backup problem before editing.

Use the actual affected file when it differs. For files managed by an administrator, follow their backup and change process.

Keep this backup with the incident or change evidence. Don’t rely solely on an automatically created .old file.

Choose the correct update scope

Warning: ssh-keygen -R removes all keys matching the specified identity. It can’t target just one matching line.

If every matching key is confirmed stale and removal is approved:

# -R removes all keys matching this exact identity.
ssh-keygen -R 'server.example.com' -f "$HOME/.ssh/known_hosts"

For port 2222, use this alternative:

ssh-keygen -R '[server.example.com]:2222' -f "$HOME/.ssh/known_hosts"

Run only the command that matches the affected identity. Expected result: all matching keys are removed from the selected file. Check that scope against the backup.

If valid keys coexist with one stale record, use a reviewed precise edit or managed update instead. Review the affected line. Keep valid records, unrelated identities, and any shared hostname fields intact.

The ssh-keygen manual documents -F, -R, and explicit file selection with -f.

Verification

Review the updated file against the backup. Confirm that only the approved stale trust changed.

After complete removal for an identity, repeat its ssh-keygen -F lookup. It should return no matching records. After a precise edit, valid matching records should remain.

5. Problem: Reconnection still fails or the replacement needs enrollment

Symptoms

  • SSH presents an authenticity prompt after removal.
  • Strict policy blocks an unknown replacement key.
  • The changed-key warning returns.
  • An automated job still fails.

Cause

Removing stale trust doesn’t verify or enroll a replacement. Another file or identity may also be involved.

Automation can use a different account, home directory, configuration, or controlled trust file than your terminal session.

Solution

Reconnect to the original intended destination with host-key checking enabled:

ssh user@server.example.com

Or, for the verified service on port 2222:

ssh -p 2222 user@server.example.com

Expected result depends on the trust policy. SSH may prompt for the unknown key or block enrollment.

If interactive enrollment is allowed, compare the prompt’s key type and complete fingerprint with the independent source. Accept only after an exact match.

If stricter policy blocks enrollment, have the verified public key installed through the approved trust-management process. Don’t weaken that policy to get a prompt.

If the warning returns, save the new warning. Check its file path, line number, identity, and presented fingerprint. Return to the relevant diagnostic step instead of removing more records.

For automation, have the owner update its actual controlled trust file after verification. An unattended job should receive verified trust through its managed process.

Controlled reconnect showing a fingerprint that matches the trusted console, followed by a repeat connection recognizing the saved server identity

Verification

Close the session, then reconnect using the same command. The verified identity should be recognized without another enrollment prompt or changed-key warning.

Record:

  • Old and new fingerprints, when available, including key types.
  • Endpoint and port.
  • Independent verification source.
  • Approver and timestamp.
  • Affected trust file and backup location.
  • Change or incident reference.
  • Result of the repeat connection.

Error Messages Table

Message or resultMeaningNext action
“REMOTE HOST IDENTIFICATION HAS CHANGED!”Presented identity conflicts with saved trustSave the evidence and verify independently
“Offending … key in …”SSH found a conflicting stored recordInspect that exact file and line
“Host key verification failed.”Server identity checking blocked accessRead the preceding diagnostic details
Authenticity prompt after removalThe replacement needs a trust decisionCompare its full fingerprint before accepting
No result from ssh-keygen -FNo match exists for that lookup and fileCheck hostname, port, alias, address, and path
Several matching recordsThe identity has multiple saved keysReview all matches before choosing an update method
New warning after an updateAnother conflict remains or the endpoint changedSave the new evidence and investigate

A password or user-key failure is a separate layer. Resolve host identity before troubleshooting account access.

Linux Configuration Issues to Check

Linux clients can use per-user and administrator-managed trust files. Start with the path in the warning.

Setting or fileCommon mistakeCorrect approach
$HOME/.ssh/known_hostsEditing another user’s fileWork with the account that produced the warning
/etc/ssh/ssh_known_hostsTrying to repair managed trust locallyUse the administrator’s change process
UserKnownHostsFileAssuming the default path appliesInspect the configured file named in diagnostics
GlobalKnownHostsFileIgnoring system-wide trustCheck managed records when the warning points to them
HostName and PortAssuming an alias uses the entered name and portConfirm the effective endpoint
HostKeyAliasSearching only the destination hostnameCheck whether configuration selects another trust identity
StrictHostKeyCheckingWeakening checks to clear the errorKeep checking enabled and retain stricter policy

A client alias can select a different destination and port:

# File: $HOME/.ssh/config
Host storage-console
    HostName server.example.com
    Port 2222
    User user

This example maps storage-console to server.example.com on port 2222, using the username user. Check any other identity settings before choosing the lookup value.

For an approved interactive workflow, StrictHostKeyChecking ask permits a decision about unknown keys. A managed environment may require StrictHostKeyChecking yes. That setting requires verified trust to be installed beforehand.

Keep the stricter policy when it applies. The ssh manual explains host authentication and client behavior.

Getting Help Without Losing Evidence

Escalate when you can’t verify the fingerprint, it differs from the trusted source, or it changes between connections. Repeatedly removing records from a failover service hides an unresolved identity problem.

For more detailed client diagnostics:

# -vvv enables detailed client diagnostics.
ssh -vvv -p 2222 user@server.example.com

Use the original destination and options, adding -vvv. Keep checking enabled and stop at any unresolved warning.

Expected result: output that describes configuration, connection details, and host-key checks. Save the relevant sections with the original warning.

The most useful client log is usually terminal output. Automation may capture that output in its job log. A remote login log alone won’t explain which local trust file caused the conflict.

Give the owner:

  • Original and current warnings.
  • Connection command, timestamp, endpoint, and port.
  • Exact trust-file path and relevant matching records.
  • Presented and independently obtained fingerprints.
  • Maintenance or incident reference.
  • Backup and approved update details.

Review logs before sharing them publicly. They can expose usernames, internal addresses, paths, and network layout. Never include private keys.

Use your distribution’s support community for packaged-client questions. For upstream behavior, consult the OpenSSH website and linked manuals. Public advice can’t prove your private server’s identity.

Prevention Tips

  • Record fingerprints before maintenance. Keep key types, endpoint details, and verified sources in trusted inventory.
  • Include identity in change records. A rebuild ticket should state how administrators will verify the replacement.
  • Maintain independent access. Document the console route for each server. A compatible USB serial console adapter can help with local hardware, but access must be established beforehand.
  • Manage automation trust centrally. Verified updates should reach the account and file each job actually uses.
  • Review failover identity policy. Every approved backend needs a documented, authenticated trust arrangement.
  • Keep recovery evidence. Retain warnings, separate backups, approval details, and verification results according to local policy.

Hashed hostnames make visual inspection harder, but ssh-keygen -F can still find them. Keep the protection and use the lookup tool.

Wrapping Up

A verified fingerprint and a precise trust-file update resolve the warning while keeping host identity checks in place. I’d spend the extra time checking the console fingerprint. Removing a record is the easy part.

StepActionApplies To
1Save the warning and connection detailsEvery changed-key warning
2Confirm the intended machine and change contextRebuilds, aliases, address changes, and failovers
3Verify the same key type and full fingerprint independentlyEvery replacement identity
4Back up and update only approved stale trustConfirmed stale records
5Reconnect and document the resultInteractive sessions and automation

Close the session and connect again to the same endpoint and port. The verified identity should be recognized without another enrollment prompt or changed-key warning.