Server Management
2025-05-22 08:21:20
Published By
KhalequzzamanAutomatically Fix SSH Host Key Verification Errors on macOS
When connecting to a remote server via SSH, you may see the error:
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!This typically happens if the server's SSH host key has changed (e.g., after a reinstallation) or if there’s a possible man-in-the-middle attack. For trusted servers, this error can be safely resolved by removing the outdated key and adding the new one. This article explains how to fix the issue manually or automatically via a script or alias on macOS.
Manual Fix (Recommended for One-Time Use)
Run the following commands in the Terminal:ssh-keygen -R <IP_ADDRESS> ssh-keyscan -H <IP_ADDRESS> >> ~/.ssh/known_hosts ssh root@<IP_ADDRESS>Example:
ssh-keygen -R 173.249.199.154 ssh-keyscan -H 173.249.199.154 >> ~/.ssh/known_hosts ssh [email protected]
Automatic Fix Using Script
You can create a helper script to automatically fix this issue when it occurs. 1. Create Script Save the following as ~/safe-ssh:#!/bin/bash
# fixssh: silently update host key and SSH into server
# Usage: fixssh <hostname_or_ip> [port] [user]
HOST="$1"
PORT="${2:-22}" # default port 22
USER="${3:-root}" # default user root
if [ -z "$HOST" ]; then
echo "Usage: fixssh <hostname_or_ip> [port] [user]"
exit 1
fi
# Remove old host key quietly
ssh-keygen -R "[$HOST]:$PORT" >/dev/null 2>&1
# Add new host key quietly
ssh-keyscan -p "$PORT" -H "$HOST" >/dev/null 2>&1
# Connect via SSH
ssh -p "$PORT" "$USER@$HOST"
2. Make Executable
chmod +x ~/safe-ssh3. Usage
~/safe-ssh 173.249.199.154Optional: Add Shell Alias To simplify usage even further, you can add an alias in your ~/.zshrc or ~/.bashrc:
# fixssh: Remove old SSH host key, add new host key silently, and SSH into the server
alias fixssh='function _fixssh() {
HOST="$1"
PORT="${2:-22}"
USER="${3:-root}"
[ -z "$HOST" ] && echo "Usage: fixssh <host> [port] [user]" && return 1
ssh-keygen -R "[$HOST]:$PORT" >/dev/null 2>&1
ssh-keyscan -p "$PORT" -H "$HOST" >/dev/null 2>&1
ssh -p "$PORT" "$USER@$HOST"
}; _fixssh'
Then reload your shell config:
source ~/.zshrc # or ~/.bashrcAnd use it like this:
fixssh 173.249.199.154Security Warning This process bypasses SSH's strict host key checking, which is a critical security feature designed to detect tampering or man-in-the-middle attacks. Use it only for servers you explicitly trust.