PyKeePass

4.1.1.post1 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a new KeePass database, open an existing one, add a new entry, find an entry by its title, retrieve its credentials, update its properties, and save the changes. Ensure you set the `KEEPASS_MASTER_PASSWORD` environment variable or replace the placeholder password.

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}")

view raw JSON →