PythonIntermediate · Windows, macOS, or Linux; Python 3.12+

Find reused SSH host-key fingerprints

Group known_hosts entries by public-key fingerprint without printing key material.

Before you begin

  • Python 3.12 or later.
  • A readable OpenSSH known_hosts file; entries are inspected locally only.
What this script changesRead-only local report. No permissions, accounts, configuration, or input files are changed. Review filenames and metadata before sharing.

Set up your example

  1. Save as security-known-host-key-reuse.py.
  2. Open a terminal in its folder.
  3. Run python "security-known-host-key-reuse.py" --help and prepare the listed input files.

This recipe uses your own local input or creates its own example output. Follow the setup steps below.

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is security-known-host-key-reuse.py.

Run the script

Run command
python "security-known-host-key-reuse.py" "known_hosts"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

Repeated identical host keys produce one group of line numbers; legitimate aliases can cause reuse.

The complete script

security-known-host-key-reuse.py
#!/usr/bin/env python3
"""Group known_hosts entries by public-key fingerprint without printing key material."""
import argparse
import sys
import json
from pathlib import Path
import base64
import hashlib
from collections import defaultdict

def main():
    parser = argparse.ArgumentParser(description='Group known_hosts entries by public-key fingerprint without printing key material.')
    parser.add_argument('known_hosts',type=Path)
    args = parser.parse_args()
    groups=defaultdict(list)
    for number,line in enumerate(args.known_hosts.read_text(encoding='utf-8').splitlines(),1):
        parts=line.split()
        if not parts or parts[0].startswith('#'):continue
        if parts[0].startswith('@'):parts=parts[1:]
        if len(parts)<3:continue
        try:blob=base64.b64decode(parts[2],validate=True)
        except ValueError:raise ValueError(f'Invalid key encoding at line {number}')
        fp=hashlib.sha256(blob).hexdigest()
        groups[(parts[1],fp)].append(number)
    for (kind,fp),lines in groups.items():
        if len(lines)>1:print(json.dumps({'type':kind,'sha256_hex':fp,'lines':lines}))

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)

Open source as plain text · Download source and sample files

How it works

  1. Group known_hosts entries by public-key fingerprint without printing key material.
  2. Arguments are explicit and expected input errors produce a message with a nonzero exit code.
  3. Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.

Make it your own

Adapt the task

Review matching lines privately; hashed hostnames remain hashed and the script does not contact the hosts.

Adjust presentation

Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An input or dependency is unavailable.

A readable OpenSSH known_hosts file; entries are inspected locally only.

Actual results differ from the example.

Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.