Remove a Stale Host Key from known_hosts with ssh-keygen
Remove a stale entry from known_hosts with ssh-keygen -R host, which keeps the old file as known_hosts.old. ssh-keygen -F finds an entry before you delete it.
A server was rebuilt and ssh refuses to connect because the stored host key no longer matches.
ssh-keygen -q -t ed25519 -N '' -f hostkey
key=$(cut -d' ' -f1,2 hostkey.pub)
printf 'web.example.com %s\nother.example.com %s\n' "$key" "$key" > known_hosts
ssh-keygen -F web.example.com -f known_hosts | head -n 1
ssh-keygen -R web.example.com -f known_hosts
cut -d' ' -f1 known_hosts
ls known_hosts*# Host web.example.com found: line 1
# Host web.example.com found: line 1
known_hosts updated.
Original contents retained as known_hosts.old
other.example.com
known_hosts
known_hosts.oldssh-keygen -F host -f file searches for a host and reports the line number, and -R host -f file deletes every entry for it. The run shows the host found on line 1, the removal, and a copy of the original saved as known_hosts.old. Only web.example.com was removed and other.example.com stayed. The options are in ssh-keygen.
Removing the key is only correct if you know why it changed. A key that changes without a rebuild can mean someone is intercepting the connection, so confirm the new fingerprint by another route before you trust it. Without -f, the command edits ~/.ssh/known_hosts. The old file keeps the names of your hosts, so delete it after use.