Home > Network Management > ssh-keyscan

ssh-keyscan: Collect SSH Host Keys

A utility to collect the public host keys of SSH servers. The collected keys are added to the `~/.ssh/known_hosts` file, allowing SSH clients to verify the server's identity when connecting. This plays a crucial role in preventing Man-in-the-Middle attacks.

Overview

ssh-keyscan collects SSH public keys from one or more hosts and outputs them to standard output. These keys are used to enhance the security of SSH connections by being added to the `known_hosts` file.

Key Features

  • Collects SSH host public keys
  • Supports updating the `known_hosts` file
  • Prevents Man-in-the-Middle (MITM) attacks
  • Scans multiple hosts or specific ports

Key Options

The main options for the ssh-keyscan command control how keys are collected, the output format, and how target hosts are specified.

Key Collection and Output

Generated command:

Try combining the commands.

Description:

`ssh-keyscan` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Learn how to effectively collect and manage SSH host keys through various usage examples of ssh-keyscan.

Scanning Keys for a Single Host

ssh-keyscan example.com

Displays all public keys for a specified host to standard output.

Adding Keys to known_hosts File

ssh-keyscan -H example.com >> ~/.ssh/known_hosts

Collects the host's keys and adds them to the `~/.ssh/known_hosts` file. Using the `-H` option to hash hostnames for storage is recommended for security.

Scanning Keys from a Specific Port

ssh-keyscan -p 2222 example.com

Scans keys from a host that provides SSH services on a port other than the default SSH port (22).

Reading a List of Hosts from a File

ssh-keyscan -f hosts.txt

When host names are listed one per line in the `hosts.txt` file, this command scans the keys for all hosts in that file.

Scanning Only Specific Key Types

ssh-keyscan -t rsa,ecdsa example.com

Collects only RSA and ECDSA key types.

Tips & Precautions

Useful tips and security considerations when using ssh-keyscan.

Security Considerations

  • Always verify that the collected keys come from a trusted source. Especially for servers you are connecting to for the first time, directly confirming the key's fingerprint with the server administrator is the most secure method.
  • The `known_hosts` file is sensitive information and should be protected with appropriate file permissions (typically 600).
  • `ssh-keyscan` only collects the server's public keys and does not attempt to authenticate to the server. Therefore, you can collect keys even without having access privileges to the server.

Usage in Automation Scripts

When provisioning new servers or managing `known_hosts` files centrally in a large-scale environment, you can include `ssh-keyscan` in automation scripts. This reduces the hassle of manual key additions and helps maintain consistent security policies.


Same category commands