Guide to ssh-keyscan on Ubuntu Linux
The ssh-keyscan utility on Ubuntu Linux is a
command-line tool used to gather and record the public SSH host keys of
remote servers. This article explains what ssh-keyscan is
used for, why it is essential for SSH security and automation, and how
to use it to manage your system’s known_hosts file.
What is ssh-keyscan Used For?
On Ubuntu and other Linux distributions, ssh-keyscan is
primarily used to pre-populate the ~/.ssh/known_hosts file.
When you connect to a remote server via SSH for the first time, your
system asks you to verify the remote host’s identity to prevent
Man-in-the-Middle (MITM) attacks.
Instead of manually connecting to every server and accepting the host
keys individually, ssh-keyscan automates this process. It
queries the remote servers, retrieves their public keys, and formats
them so they can be easily appended to your local verification list.
Why Use ssh-keyscan?
- Automation and Scripting: Interactive SSH prompts
(“Are you sure you want to continue connecting?”) halt non-interactive
scripts. Using
ssh-keyscanallows scripts, CI/CD pipelines, and configuration management tools (like Ansible) to connect to remote servers without user intervention. - Bulk Key Gathering: It can scan multiple IP addresses or hostnames simultaneously, saving time when managing large networks.
- Troubleshooting: It helps verify if a remote server’s SSH service is active and displays which public key types (e.g., RSA, ECDSA, Ed25519) the server supports.
How to Use ssh-keyscan on Ubuntu
The ssh-keyscan tool is part of the
openssh-client package, which is installed by default on
Ubuntu. Below are the most common ways to use it.
1. Scan a Single Host
To view the public SSH keys of a remote server, run the command followed by the domain name or IP address:
ssh-keyscan github.com2. Append Keys to the known_hosts File
To automatically trust a remote server by adding its public keys to
your local known_hosts file, redirect the command
output:
ssh-keyscan github.com >> ~/.ssh/known_hosts3. Scan Multiple Hosts from a File
If you have a list of servers, you can save their IP addresses or
hostnames in a text file (e.g., hosts.txt) and scan them
all at once:
ssh-keyscan -f hosts.txt >> ~/.ssh/known_hosts4. Fetch Specific Key Types
By default, ssh-keyscan fetches all available key types.
If you only want a specific algorithm, such as Ed25519, use the
-t option:
ssh-keyscan -t ed25519 192.168.1.50 >> ~/.ssh/known_hostsSecurity Consideration
While ssh-keyscan is highly convenient, it does not
verify the authenticity of the keys it retrieves; it simply downloads
whatever key the remote server presents at that moment. For maximum
security, you should verify the retrieved fingerprints against an
out-of-band source before permanently trusting them in a production
environment.