SSH Public Key Parser
sshpubkeys is a Python library for parsing SSH public keys. It supports various key types (RSA, DSA, ECDSA, Ed25519) and can handle authorized_keys file formats, including options like 'command=' or 'no-port-forwarding'. The current version is 3.3.1, and it maintains an active, feature-driven release cadence.
Warnings
- breaking Support for Python 2.6 and Python 3.3 was dropped.
- breaking Handling of DSA keys changed; 'loose mode' no longer accepts non-standard DSA key lengths.
- breaking The internal ECDSA implementation dependency shifted from `ecdsa` to `cryptography`. While generally internal, direct interaction with `_key.ecdsa_key` or similar internal objects will break.
- gotcha Python 3.5 support was temporarily broken in versions immediately preceding `3.3.1`, despite earlier support.
- gotcha A typo `ed25516` was corrected to `ed25519` for the key type. While primarily an internal fix, users relying on string comparisons with the incorrect type might be affected.
Install
-
pip install sshpubkeys
Imports
- SSHKey
from sshpubkeys import SSHKey
- InvalidKeyException
from sshpubkeys import InvalidKeyException
Quickstart
from sshpubkeys import SSHKey, InvalidKeyException
import os
# This is a dummy example key. Replace with a real key or load from a file.
# For actual use, avoid hardcoding keys directly in code.
# A real key might look like: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCq2z/t... user@example.com'
example_public_key_string = os.environ.get(
'SSH_PUBLIC_KEY',
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw0Y1c/tFk9k/N... dummy_key@example.com'
)
try:
key = SSHKey(example_public_key_string)
print(f"Key type: {key.key_type}")
print(f"Key length: {key.length}")
print(f"Fingerprint (MD5): {key.hash_md5}")
print(f"Fingerprint (SHA256): {key.hash_sha256}")
print(f"Comment: {key.comment}")
key.verify_length() # Ensures key length is standard for its type
print("Key is valid and has standard length.")
except InvalidKeyException as e:
print(f"Error parsing SSH key: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")