PyKerberos (krb5)
krb5 is a Python library that provides direct bindings to the MIT Kerberos 5 C API, enabling Python applications to interact with Kerberos for authentication and security services at a low level. The current version is 0.9.0, with regular releases (typically a few times a year) maintaining compatibility and extending its API coverage.
Warnings
- breaking Python version support is frequently updated. Version 0.9.0 requires Python 3.9+ (dropped 3.8 in v0.8.0). Prior versions 0.7.0 and 0.4.0 also dropped support for Python 3.7 and 3.6, respectively.
- breaking Since version 0.4.0, Cython is a mandatory build dependency. The source distribution (sdist) no longer includes the pre-compiled `.c` files, requiring Cython to be available during installation.
- gotcha This library provides low-level bindings to the Kerberos C API. For higher-level, more Pythonic interactions with Kerberos (especially involving GSSAPI), `python-gssapi` is often a more suitable and recommended library.
- gotcha While v0.9.0 adds support for Python Free-Threading (PEP 779), the library has limited testing in this scenario and 'does not aim to be thread safe out of the box'.
Install
-
pip install krb5
Imports
- krb5
import krb5
- Krb5Error
from krb5.exceptions import Krb5Error
Quickstart
import krb5
from krb5.exceptions import Krb5Error
import os
try:
# Initialize a Kerberos context
ctx = krb5.init_context()
print("Kerberos context initialized successfully.")
# Example: Parse a principal name
# Replace 'testuser@EXAMPLE.COM' with a valid principal in your Kerberos environment
# or set KRB5_PRINCIPAL environment variable for example.
principal_name = os.environ.get('KRB5_PRINCIPAL', 'host/localhost@REALM.TEST')
# Using with statement ensures proper cleanup of the context and principal
with ctx:
with krb5.parse_name(ctx, principal_name) as principal:
print(f"Parsed principal: {principal.name}")
print(f"Principal Realm: {principal.realm}")
except Krb5Error as e:
print(f"Kerberos Error: {e.message} (Code: {e.error_code})")
print("Ensure Kerberos is configured correctly and system libraries are installed.")
except Exception as e:
print(f"An unexpected error occurred: {e}")