PyKeePass
PyKeePass is a Python library that enables interaction with KeePass databases, supporting both KDBX3 and KDBX4 formats. It allows users to read, create, update, and save entries and groups within a KeePass file. The library is actively maintained with frequent releases, typically every few months.
Warnings
- breaking Starting with version 4.0.0, path arguments for methods like `find_groups`, `find_entries`, `add_group`, and `add_entry` changed from a single string (e.g., 'Group/Subgroup') to a list of strings representing the hierarchical components (e.g., ['Group', 'Subgroup']).
- gotcha Methods like `find_entries()` and `find_groups()` return a *list* of matching objects by default, even if only one item matches. Directly accessing attributes (e.g., `entry.password`) on the result without specifying `first=True` or indexing the list (`[0]`) will result in an `AttributeError`.
- behavioral As of version 4.1.0, the `Entry.tags` property now returns an empty list `[]` when an entry has no tags defined, instead of `None`. Code that checks for `if entry.tags is None:` might need adjustment to `if not entry.tags:` or `if len(entry.tags) == 0:`.
Install
-
pip install pykeepass
Imports
- PyKeePass
from pykeepass import PyKeePass
Quickstart
import os
from pykeepass import PyKeePass, create_database
DB_PATH = 'my_database.kdbx'
MASTER_PASSWORD = os.environ.get('KEEPASS_MASTER_PASSWORD', 'supersecurepassword')
# Create a new KeePass database
if not os.path.exists(DB_PATH):
print(f"Creating new database at {DB_PATH}")
kp = create_database(filename=DB_PATH, password=MASTER_PASSWORD)
# Add a root group if it doesn't exist (create_database usually handles this)
# kp.add_group(kp.root_group, 'General')
kp.save()
# Open an existing KeePass database
print(f"Opening database: {DB_PATH}")
kp = PyKeePass(DB_PATH, password=MASTER_PASSWORD)
# Add a new entry if it doesn't exist
if not kp.find_entries(title='Example Entry', first=True):
print("Adding new entry: 'Example Entry'")
# The path argument should be a list of strings for group hierarchy (v4.0.0+)
entry = kp.add_entry(kp.root_group, 'Example Entry', 'testuser', 'entry_password_123', notes='This is a test entry.')
print(f"Added entry: {entry.title} ({entry.username})")
else:
print("Entry 'Example Entry' already exists.")
# Find an entry and retrieve its password
entry = kp.find_entries(title='Example Entry', first=True) # Use first=True for a single entry
if entry:
print(f"Found entry '{entry.title}'. Username: {entry.username}, Password: {entry.password}")
# Update an entry
entry.notes = 'Updated notes for the test entry.'
entry.tags = ['web', 'test']
print(f"Entry notes updated: {entry.notes}")
print(f"Entry tags updated: {entry.tags}")
else:
print("Entry 'Example Entry' not found.")
# Save changes to the database
kp.save()
print("Database saved successfully.")
# Clean up (optional)
# os.remove(DB_PATH)
# print(f"Cleaned up: Removed {DB_PATH}")