### Install pykeepass Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Install the necessary package for using pykeepass. ```bash sudo apt install python3-lxml pip install pykeepass ``` -------------------------------- ### Export database as XML Source: https://context7.com/libkeepass/pykeepass/llms.txt Access or dump the raw decrypted XML of the database for inspection or backup purposes using `kp.xml()` to get bytes or `kp.dump_xml()` to save to a file. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') # Get XML as bytes xml_bytes = kp.xml() print(xml_bytes[:200]) # b"\n..." # Dump XML to file kp.dump_xml('vault_export.xml') ``` -------------------------------- ### Find and manipulate groups in KeePass Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Examples for finding groups by name or regex, accessing subgroups, creating new groups, deleting groups, and moving groups. Saving the database is necessary after changes. ```python >>> kp.groups [Group: "foo", Group "foobar", Group: "social", Group: "social/foo_subgroup"] >>> kp.find_groups(name='foo', first=True) Group: "foo" >>> kp.find_groups(name='foo.*', regex=True) [Group: "foo", Group "foobar"] >>> kp.find_groups(path=['social'], regex=True) [Group: "social", Group: "social/foo_subgroup"] >>> kp.find_groups(name='social', first=True).subgroups [Group: "social/foo_subgroup"] >>> kp.root_group Group: "/" # add a new group to the Root group >>> group = kp.add_group(kp.root_group, 'social') # add a new group to the social group >>> group2 = kp.add_group(group, 'gmail') Group: "social/gmail" # save the database >>> kp.save() # delete a group >>> kp.delete_group(group) # move a group >>> kp.move_group(group2, kp.root_group) # save the database >>> kp.save() # change creation time >>> from datetime import datetime, timezone >>> group.ctime = datetime(2023, 1, 1, tzinfo=timezone.utc) # update modification or access time >>> group.touch(modify=True) ``` -------------------------------- ### Get, set, and delete custom string properties on an entry Source: https://context7.com/libkeepass/pykeepass/llms.txt Manage arbitrary key-value string data associated with an entry. Custom properties can be marked as protected. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='AWS Console', first=True) # Set custom properties entry.set_custom_property('AccountID', '123456789012') entry.set_custom_property('Region', 'us-east-1') entry.set_custom_property('SecretToken', 'tok_abc123', protect=True) # mark as protected # Get a custom property print(entry.get_custom_property('AccountID')) # '123456789012' # Check if a property is protected print(entry.is_custom_property_protected('SecretToken')) # True # List all custom properties print(entry.custom_properties) # {'AccountID': '123456789012', 'Region': 'us-east-1', 'SecretToken': 'tok_abc123'} # Delete a custom property entry.delete_custom_property('Region') kp.save() ``` -------------------------------- ### Entry custom properties — Get, set, and delete custom string fields Source: https://context7.com/libkeepass/pykeepass/llms.txt Allows storing and managing arbitrary key-value string data on an entry, beyond the standard KeePass fields. Supports setting, getting, checking protection status, listing, and deleting custom properties. ```APIDOC ## Entry custom properties — Get, set, and delete custom string fields Store arbitrary key-value string data on an entry beyond the built-in fields. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='AWS Console', first=True) # Set custom properties entry.set_custom_property('AccountID', '123456789012') entry.set_custom_property('Region', 'us-east-1') entry.set_custom_property('SecretToken', 'tok_abc123', protect=True) # mark as protected # Get a custom property print(entry.get_custom_property('AccountID')) # '123456789012' # Check if a property is protected print(entry.is_custom_property_protected('SecretToken')) # True # List all custom properties print(entry.custom_properties) # {'AccountID': '123456789012', 'Region': 'us-east-1', 'SecretToken': 'tok_abc123'} # Delete a custom property entry.delete_custom_property('Region') kp.save() ``` ``` -------------------------------- ### Move a group Source: https://context7.com/libkeepass/pykeepass/llms.txt Moves a specified subgroup to a new parent group. The example also shows how to find groups and print the new path of the moved subgroup. ```APIDOC ## Move a group Moves a specified subgroup to a new parent group. The example also shows how to find groups and print the new path of the moved subgroup. ```python subgroup = kp.find_groups(name='email', first=True) new_parent = kp.find_groups(name='archive', first=True) kp.move_group(subgroup, new_parent) print(subgroup.path) # ['archive', 'email'] ``` ``` -------------------------------- ### PyKeePass.find_entries Source: https://context7.com/libkeepass/pykeepass/llms.txt Returns entries matching all provided parameters. Supports exact match, XSLT-style regex, path lookups, custom string fields, tags, UUIDs, OTP, and autotype fields. Use `first=True` to get a single result or `None`, or `first=False` (default) to get a list. ```APIDOC ## `PyKeePass.find_entries` — Search for entries Returns entries matching all provided parameters. Supports exact match, XSLT-style regex, path lookups, custom string fields, tags, UUIDs, OTP, and autotype fields. Use `first=True` to get a single result or `None`, or `first=False` (default) to get a list. ```python from pykeepass import PyKeePass import uuid lp = PyKeePass('vault.kdbx', password='pass') # Find by title (exact) entry = lp.find_entries(title='Gmail', first=True) print(entry.password) # 'myGmailPass!' # Find by regex across multiple fields entries = lp.find_entries(title='Git.*', url='.*github.*', regex=True) for e in entries: print(e.title, e.username) ``` ``` -------------------------------- ### Delete or Move Groups in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Provides examples for deleting a group and all its contents, or for moving a group to a different parent. The database must be saved to apply these changes. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') ``` -------------------------------- ### `debug_setup` — Enable debug logging Source: https://context7.com/libkeepass/pykeepass/llms.txt Activates verbose XPath query logging to assist in understanding how searches are executed internally. ```APIDOC ## `debug_setup` — Enable debug logging Activates verbose XPath query logging to help understand how searches are executed internally. ```python from pykeepass import PyKeePass from pykeepass.pykeepass import debug_setup debug_setup() kp = PyKeePass('vault.kdbx', password='pass') kp.find_entries(title='Gmail', first=True) # DEBUG:pykeepass.pykeepass:xpath query: //Entry[not(ancestor::History)][String/Key[text()="Title"]/../Value[text()="Gmail"]] # DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] # DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] # Entry: "social/Gmail (user@gmail.com)" ``` ``` -------------------------------- ### create_database Source: https://context7.com/libkeepass/pykeepass/llms.txt Creates a new KDBX database file at the specified path with the given credentials. Accepts a password, a keyfile path, or a precomputed transformed key. Returns a PyKeePass instance ready for use. ```APIDOC ## `create_database` — Create a new KeePass database Creates a new KDBX database file at the specified path with the given credentials. Accepts a password, a keyfile path, or a precomputed transformed key. Returns a `PyKeePass` instance ready for use. ```python from pykeepass import create_database # Create with password only lp = create_database('new_vault.kdbx', password='MySecretPass!') # Create with both password and keyfile lp = create_database('vault_with_key.kdbx', password='MySecretPass!', keyfile='/path/to/vault.key') print(lp.version) # e.g. (4, 0) print(lp.encryption_algorithm) # 'aes256', 'chacha20', or 'twofish' print(lp.kdf_algorithm) # 'aeskdf', 'argon2', or 'argon2id' lp.save() ``` ``` -------------------------------- ### Enable debug logging Source: https://context7.com/libkeepass/pykeepass/llms.txt Activates verbose XPath query logging to help understand how searches are executed internally. Call `debug_setup()` before initializing `PyKeePass`. ```python from pykeepass import PyKeePass from pykeepass.pykeepass import debug_setup debug_setup() kp = PyKeePass('vault.kdbx', password='pass') kp.find_entries(title='Gmail', first=True) # DEBUG:pykeepass.pykeepass:xpath query: //Entry[not(ancestor::History)][String/Key[text()="Title"]/../Value[text()="Gmail"]] # DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] # DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] # Entry: "social/Gmail (user@gmail.com)" ``` -------------------------------- ### Enable Debugging in PyKeePass Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Call `debug_setup()` to enable detailed logging during test execution. This helps in diagnosing issues by showing internal queries and data access. ```python from pykeepass.pykeepass import debug_setup debug_setup() >>> kp.entries[0] DEBUG:pykeepass.pykeepass:xpath query: //Entry DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] DEBUG:pykeepass.pykeepass:xpath query: String/Key[text()="Title"]/../Value DEBUG:pykeepass.pykeepass:xpath query: String/Key[text()="UserName"]/../Value Entry: "root_entry (foobar_user)" ``` -------------------------------- ### Attach files to entries using add_binary and add_attachment Source: https://context7.com/libkeepass/pykeepass/llms.txt Binary data is stored once at the database level and referenced by entry attachments. This snippet shows how to read a file, add it as a binary, and then attach it to an entry. It also covers listing, finding, and deleting attachments and binaries. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='SSH Keys', first=True) # Read a file and add it as a binary with open('/home/user/.ssh/id_rsa.pub', 'rb') as f: pubkey_data = f.read() binary_id = kp.add_binary(pubkey_data) # returns int ID print(kp.binaries[binary_id]) # b'ssh-rsa AAAA...' # Attach the binary to the entry with a filename attachment = entry.add_attachment(binary_id, 'id_rsa.pub') print(attachment) # Attachment: 'id_rsa.pub' -> 0 print(attachment.filename) # 'id_rsa.pub' print(attachment.id) # 0 print(attachment.data) # b'ssh-rsa AAAA...' print(attachment.entry) # Entry: "SSH Keys (...)" # List all attachments on entry print(entry.attachments) # [Attachment: 'id_rsa.pub' -> 0] # List all attachments in the database print(kp.attachments) # Find attachments by filename results = kp.find_attachments(filename='id_rsa.pub') results_regex = kp.find_attachments(filename=r'.*\.pub', regex=True) # Delete just the reference (binary data remains) entry.delete_attachment(attachment) # Delete the binary and all references to it kp.delete_binary(binary_id) kp.save() ``` -------------------------------- ### PyKeePass.__init__ Source: https://context7.com/libkeepass/pykeepass/llms.txt Loads and decrypts a .kdbx file. Accepts a file path or a file-like stream object. Raises CredentialsError on wrong password/keyfile, HeaderChecksumError on a corrupt header, and PayloadChecksumError on corrupted payload blocks. ```APIDOC ## `PyKeePass.__init__` — Open an existing KeePass database Loads and decrypts a `.kdbx` file. Accepts a file path or a file-like stream object. Raises `CredentialsError` on wrong password/keyfile, `HeaderChecksumError` on a corrupt header, and `PayloadChecksumError` on corrupted payload blocks. ```python from pykeepass import PyKeePass from pykeepass.exceptions import CredentialsError, HeaderChecksumError # Open with password try: lp = PyKeePass('vault.kdbx', password='MySecretPass!') except CredentialsError: print("Wrong password or keyfile") except HeaderChecksumError: print("Database file is corrupt or not a KeePass file") # Open with keyfile lp = PyKeePass('vault.kdbx', password='MySecretPass!', keyfile='vault.key') # Open from a stream (e.g., from network or in-memory) import io with open('vault.kdbx', 'rb') as f: data = io.BytesIO(f.read()) lp = PyKeePass(data, password='MySecretPass!') # Cache transformed key to speed up subsequent opens transformed_key = lp.transformed_key lp2 = PyKeePass('vault.kdbx', transformed_key=transformed_key) # Access header info without decrypting the payload lp_header_only = PyKeePass('vault.kdbx', password='MySecretPass!', decrypt=False) print(lp_header_only.version) # (4, 0) ``` ``` -------------------------------- ### Create New KeePass Database Source: https://context7.com/libkeepass/pykeepass/llms.txt Creates a new KDBX database file. Supports password-only or password with keyfile authentication. Displays database version, encryption, and KDF algorithms. ```python from pykeepass import create_database # Create with password only kp = create_database('new_vault.kdbx', password='MySecretPass!') # Create with both password and keyfile kp = create_database('vault_with_key.kdbx', password='MySecretPass!', keyfile='/path/to/vault.key') print(kp.version) # e.g. (4, 0) print(kp.encryption_algorithm) # 'aes256', 'chacha20', or 'twofish' print(kp.kdf_algorithm) # 'aeskdf', 'argon2', or 'argon2id' kp.save() ``` -------------------------------- ### Database metadata properties Source: https://context7.com/libkeepass/pykeepass/llms.txt Read and write database-level metadata including name, description, default username, and credential policy. This includes changing the master password and saving the changes. ```python from pykeepass import PyKeePass from datetime import datetime, timezone kp = PyKeePass('vault.kdbx', password='pass') # Database info print(kp.database_name) # 'My Passwords' print(kp.database_description) # 'Personal vault' print(kp.default_username) # 'john.doe' kp.database_name = 'Company Vault' kp.database_description = 'All company credentials' kp.default_username = 'admin' # Credential change policy print(kp.credchange_date) # last password change datetime print(kp.credchange_required_days) # -1 (disabled) or days print(kp.credchange_recommended_days) # -1 (disabled) or days kp.credchange_required_days = 180 # require change every 6 months kp.credchange_recommended_days = 90 # recommend change every 3 months print(kp.credchange_required) # True if overdue print(kp.credchange_recommended) # True if overdue # Change the master password (update in-memory, then save) kp.password = 'NewStr0ngMast3rP@ss!' kp.save() ``` -------------------------------- ### Trash Entry in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Shows how to move an entry to the Recycle Bin. This operation will raise an exception if the entry is already in the bin. The database needs to be saved to confirm the action. ```python from pykeepass import PyKeePass from pykeepass.exceptions import UnableToSendToRecycleBin kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='OldService', first=True) try: kp.trash_entry(entry) print("Moved to:", kp.recyclebin_group) # Group: "Recycle Bin" except UnableToSendToRecycleBin: print("Entry is already in the recycle bin") kp.save() ``` -------------------------------- ### Open Existing KeePass Database Source: https://context7.com/libkeepass/pykeepass/llms.txt Loads and decrypts a KDBX file using password, keyfile, or a precomputed transformed key for faster access. Handles credential and checksum errors. Can open from streams and access header info without full decryption. ```python from pykeepass import PyKeePass from pykeepass.exceptions import CredentialsError, HeaderChecksumError # Open with password try: kp = PyKeePass('vault.kdbx', password='MySecretPass!') except CredentialsError: print("Wrong password or keyfile") except HeaderChecksumError: print("Database file is corrupt or not a KeePass file") # Open with keyfile kp = PyKeePass('vault.kdbx', password='MySecretPass!', keyfile='vault.key') # Open from a stream (e.g., from network or in-memory) import io with open('vault.kdbx', 'rb') as f: data = io.BytesIO(f.read()) kp = PyKeePass(data, password='MySecretPass!') # Cache transformed key to speed up subsequent opens transformed_key = kp.transformed_key kp2 = PyKeePass('vault.kdbx', transformed_key=transformed_key) # Access header info without decrypting the payload kp_header_only = PyKeePass('vault.kdbx', password='MySecretPass!', decrypt=False) print(kp_header_only.version) # (4, 0) ``` -------------------------------- ### Add New Entry in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Shows how to create new entries in a KeePass database, from basic entries to fully-featured ones including expiry, OTP, tags, icons, and notes. Ensure the database is saved after adding entries. ```python from pykeepass import PyKeePass from pykeepass.icons import icons from datetime import datetime, timezone kp = PyKeePass('vault.kdbx', password='pass') group = kp.find_groups(name='social', first=True) # Basic entry entry = kp.add_entry(group, 'Twitter', 'myuser', 'tw1tt3rP@ss') ``` ```python from datetime import datetime, timezone, timedelta entry = kp.add_entry( kp.root_group, title='AWS Console', username='admin@company.com', password='Str0ngP@ss!', url='https://console.aws.amazon.com', notes='Primary AWS account - prod environment', tags=['work', 'aws', 'cloud'], expiry_time=datetime.now(timezone.utc) + timedelta(days=90), otp='otpauth://totp/AWS:admin@company.com?secret=JBSWY3DPEHPK3PXP&issuer=AWS', icon=icons.WorldComputer, force_creation=False ) print(entry) # Entry: "AWS Console (admin@company.com)" print(entry.expired) # False (not yet expired) kp.save() ``` -------------------------------- ### Manage attachments in KeePass Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Demonstrates adding binary data as attachments to entries, referencing them, accessing attachment details, listing all attachments, searching by filename, and deleting attachments. ```python >>> e = kp.add_entry(kp.root_group, title='foo', username='', password='') # add attachment data to the db >>> binary_id = kp.add_binary(b'Hello world') >>> kp.binaries [b'Hello world'] # add attachment reference to entry >>> a = e.add_attachment(binary_id, 'hello.txt') >>> a Attachment: 'hello.txt' -> 0 # access attachments >>> a Attachment: 'hello.txt' -> 0 >>> a.id 0 >>> a.filename 'hello.txt' >>> a.data b'Hello world' >>> e.attachments [Attachment: 'hello.txt' -> 0] # list all attachments in the database >>> kp.attachments [Attachment: 'hello.txt' -> 0] # search attachments >>> kp.find_attachments(filename='hello.txt') [Attachment: 'hello.txt** -> 0] # delete attachment reference >>> e.delete_attachment(a) # or, delete both attachment reference and binary >>> kp.delete_binary(binary_id** ``` -------------------------------- ### Add, delete, and move entries in KeePass Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Demonstrates adding new entries to specific groups, deleting entries, and moving entries between groups. Remember to save the database after modifications. ```python # add a new entry to the Root group >>> kp.add_entry(kp.root_group, 'testing', 'foo_user', 'passw0rd') Entry: "testing (foo_user)" # add a new entry to the social group >>> group = kp.find_groups(name='social', first=True) >>> entry = kp.add_entry(group, 'testing', 'foo_user', 'passw0rd') Entry: "testing (foo_user)" # save the database >>> kp.save() # delete an entry >>> kp.delete_entry(entry) # move an entry >>> kp.move_entry(entry, kp.root_group) # save the database >>> kp.save() # change creation time >>> from datetime import datetime, timezone >>> entry.ctime = datetime(2023, 1, 1, tzinfo=timezone.utc) # update modification or access time >>> entry.touch(modify=True) # save entry history >>> entry.save_history() ``` -------------------------------- ### Database metadata properties — Name, description, and credential policy Source: https://context7.com/libkeepass/pykeepass/llms.txt Allows reading and writing database-level metadata, including name, description, default username, and master key change policies. ```APIDOC ## Database metadata properties — Name, description, and credential policy Read and write database-level metadata including name, description, default username, and master key change policies. ```python from pykeepass import PyKeePass from datetime import datetime, timezone kp = PyKeePass('vault.kdbx', password='pass') # Database info print(kp.database_name) # 'My Passwords' print(kp.database_description) # 'Personal vault' print(kp.default_username) # 'john.doe' kp.database_name = 'Company Vault' kp.database_description = 'All company credentials' kp.default_username = 'admin' # Credential change policy print(kp.credchange_date) # last password change datetime print(kp.credchange_required_days) # -1 (disabled) or days print(kp.credchange_recommended_days) # -1 (disabled) or days kp.credchange_required_days = 180 # require change every 6 months kp.credchange_recommended_days = 90 # recommend change every 3 months print(kp.credchange_required) # True if overdue print(kp.credchange_recommended) # True if overdue # Change the master password (update in-memory, then save) kp.password = 'NewStr0ngMast3rP@ss!' kp.save() ``` ``` -------------------------------- ### Assigning Built-in Icons to Groups and Entries Source: https://context7.com/libkeepass/pykeepass/llms.txt Use named constants from `pykeepass.icons` to assign icons when creating groups and entries. Icons are represented as simple string constants. ```python from pykeepass import PyKeePass, create_database from pykeepass.icons import icons kp = create_database('vault.kdbx', password='pass') # Create groups and entries with meaningful icons email_group = kp.add_group(kp.root_group, 'Email', icon=icons.EMail) server_group = kp.add_group(kp.root_group, 'Servers', icon=icons.NetworkServer) finance_group = kp.add_group(kp.root_group, 'Finance', icon=icons.Homebanking) entry = kp.add_entry(email_group, 'Gmail', 'user@gmail.com', 'pass', icon=icons.World) entry2 = kp.add_entry(server_group, 'prod-web-01', 'ubuntu', 'ssh_key_used', icon=icons.Console) # Icons are simple string constants print(icons.EMail) # '19' print(icons.NetworkServer) # '3' print(icons.Folder) # '48' print(icons.Star) # '61' kp.save() ``` -------------------------------- ### PyKeePass.reload Source: https://context7.com/libkeepass/pykeepass/llms.txt Re-reads the database file from disk using the credentials supplied at open time, refreshing the in-memory state to match what is on disk. ```APIDOC ## `PyKeePass.reload` — Reload database from disk Re-reads the database file from disk using the credentials supplied at open time, refreshing the in-memory state to match what is on disk. ```python from pykeepass import PyKeePass lp = PyKeePass('vault.kdbx', password='pass') # ... some external process modified the file ... lp.reload() print(lp.entries) # reflects the updated file ``` ``` -------------------------------- ### Move a group to the Recycle Bin Source: https://context7.com/libkeepass/pykeepass/llms.txt Sends a group to the Recycle Bin. The group must be empty before it can be trashed. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') group = kp.find_groups(name='old_project', first=True) kp.empty_group(group) kp.trash_group(group) kp.save() ``` -------------------------------- ### Read and write entry fields Source: https://context7.com/libkeepass/pykeepass/llms.txt Access and modify standard fields of an entry, including title, password, notes, tags, URL, and timestamps. Use `touch(modify=True)` to update modification and access times. ```python from pykeepass import PyKeePass from datetime import datetime, timezone kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='Gmail', first=True) # Read standard fields print(entry.title) # 'Gmail' print(entry.username) # 'user@gmail.com' print(entry.password) # 'g0ogleP@ss!' print(entry.url) # 'https://mail.google.com' print(entry.notes) # 'Personal Google account' print(entry.tags) # ['personal', 'email'] print(entry.otp) # 'otpauth://totp/...' print(entry.icon) # '19' (EMail icon) print(entry.uuid) # UUID('...') print(entry.path) # ['social', 'Gmail'] print(entry.group) # Group: "social" # Write standard fields entry.title = 'Gmail (Personal)' entry.password = 'newStr0ngP@ss!' entry.notes = 'Updated 2025' entry.tags = ['personal', 'email', 'google'] entry.url = 'https://mail.google.com' # Timestamps print(entry.ctime) # datetime(2023, 1, 1, tzinfo=timezone.utc) print(entry.mtime) # last modification time print(entry.atime) # last access time entry.ctime = datetime(2024, 6, 1, tzinfo=timezone.utc) entry.touch(modify=True) # updates atime and mtime to now # Expiry entry.expires = True entry.expiry_time = datetime(2025, 12, 31, tzinfo=timezone.utc) print(entry.expired) # False (if today < 2025-12-31) # Autotype print(entry.autotype_enabled) # True print(entry.autotype_sequence) # '{USERNAME}{TAB}{PASSWORD}{ENTER}' print(entry.autotype_window) # 'Gmail - *' entry.autotype_sequence = '{USERNAME}{TAB}{PASSWORD}{ENTER}' entry.autotype_window = 'Gmail*' kp.save() ``` -------------------------------- ### Find Groups in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Explains how to search for groups using various criteria like name, path, UUID, notes, or regex. It covers retrieving all groups, finding a single group, and accessing subgroups. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') # All groups print(kp.groups) # [Group: "social", Group: "social/twitter", Group: "work", ...] # Find by exact name group = kp.find_groups(name='social', first=True) # Find by regex groups = kp.find_groups(name='soc.*', regex=True) # Find by full path group = kp.find_groups(path=['work', 'cloud']) # Find subgroups of a given group parent = kp.find_groups(name='work', first=True) print(parent.subgroups) # [Group: "work/cloud", Group: "work/on-prem"] # Root group print(kp.root_group) # Group: "/" print(kp.root_group.entries) # entries at the top level ``` -------------------------------- ### Entry history — Save and manage entry version history Source: https://context7.com/libkeepass/pykeepass/llms.txt Enables saving and managing version history for entries. Allows saving the current state, modifying the entry, inspecting historical versions, deleting specific history items, or clearing all history. ```APIDOC ## Entry history — Save and manage entry version history KeePass supports versioned history for entries. History must be saved explicitly. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='GitHub', first=True) # Save current state to history before modifying entry.save_history() # Modify the entry entry.password = 'updatedP@ss2025!' kp.save() # Inspect history for h in entry.history: print(h, h.mtime) # Delete a specific history item old = entry.history[0] entry.delete_history(old) # Clear all history entry.delete_history(all=True) kp.save() ``` ``` -------------------------------- ### Load and manipulate KeePass database Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Load a KeePass database, retrieve entries, find groups and entries, update entry details, create new groups and entries, and save changes. ```python from pykeepass import PyKeePass # load database >>> kp = PyKeePass('db.kdbx', password='somePassw0rd') # get all entries >>> kp.entries [Entry: "foo_entry (myusername)", Entry: "foobar_entry (myusername)", ...] # find any group by its name >>> group = kp.find_groups(name='social', first=True) # get the entries in a group >>> group.entries [Entry: "social/facebook (myusername)", Entry: "social/twitter (myusername)"] # find any entry by its title >>> entry = kp.find_entries(title='facebook', first=True) # retrieve the associated password and OTP information >>> entry.password 's3cure_p455w0rd' >>> entry.otp otpauth://totp/test:lkj?secret=TEST%3D%3D%3D%3D&period=30&digits=6&issuer=test # update an entry >>> entry.notes = 'primary facebook account' # create a new group >>> group = kp.add_group(kp.root_group, 'email') # create a new entry >>> kp.add_entry(group, 'gmail', 'myusername', 'myPassw0rdXX') Entry: "email/gmail (myusername)" # save database >>> kp.save() ``` -------------------------------- ### Add New Group in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Details the process of creating new groups, both at the top level and as nested subgroups. Options for adding icons and notes to groups are also shown. Remember to save the database after creation. ```python from pykeepass import PyKeePass from pykeepass.icons import icons kp = PyKeePass('vault.kdbx', password='pass') # Top-level group social = kp.add_group(kp.root_group, 'social') # Nested group with icon and notes email_group = kp.add_group( social, 'email', icon=icons.EMail, notes='All email service credentials' ) print(email_group) # Group: "social/email" kp.save() ``` -------------------------------- ### `PyKeePass.add_binary` / `Entry.add_attachment` — Attach files to entries Source: https://context7.com/libkeepass/pykeepass/llms.txt Allows attaching files to entries. Binary data is stored once at the database level and can be referenced by multiple entry attachments. ```APIDOC ## `PyKeePass.add_binary` / `Entry.add_attachment` — Attach files to entries Binary data is stored once at the database level and referenced by one or more entry attachments. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='SSH Keys', first=True) # Read a file and add it as a binary with open('/home/user/.ssh/id_rsa.pub', 'rb') as f: pubkey_data = f.read() binary_id = kp.add_binary(pubkey_data) # returns int ID print(kp.binaries[binary_id]) # b'ssh-rsa AAAA...' # Attach the binary to the entry with a filename attachment = entry.add_attachment(binary_id, 'id_rsa.pub') print(attachment) # Attachment: 'id_rsa.pub' -> 0 print(attachment.filename) # 'id_rsa.pub' print(attachment.id) # 0 print(attachment.data) # b'ssh-rsa AAAA...' print(attachment.entry) # Entry: "SSH Keys (...) " # List all attachments on entry print(entry.attachments) # [Attachment: 'id_rsa.pub' -> 0] # List all attachments in the database print(kp.attachments) # Find attachments by filename results = kp.find_attachments(filename='id_rsa.pub') results_regex = kp.find_attachments(filename=r'.*\.pub', regex=True) # Delete just the reference (binary data remains) entry.delete_attachment(attachment) # Delete the binary and all references to it kp.delete_binary(binary_id) kp.save() ``` ``` -------------------------------- ### Entry.ref and PyKeePass.deref — Field references between entries Source: https://context7.com/libkeepass/pykeepass/llms.txt Facilitates creating cross-entry references using KeePass field reference syntax, enabling sharing of sensitive data like passwords without duplication. Supports generating reference strings and dereferencing them to retrieve actual values. ```APIDOC ## Entry.ref and PyKeePass.deref — Field references between entries Create cross-entry references using KeePass field reference syntax. Useful for sharing a username or password across multiple entries without duplication. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') source = kp.find_entries(title='MasterAccount', first=True) target = kp.find_entries(title='DerivedService', first=True) # Generate a field reference string pointing to source's password ref_str = source.ref('password') print(ref_str) # '{REF:P@I:ABCDEF1234567890...}' # Set another entry's password to this reference target.password = ref_str # Dereference to get the actual value print(kp.deref(target.password)) # resolves to source.password value # Dereference directly on entry print(target.deref('password')) # same result kp.save() ``` ``` -------------------------------- ### PyKeePass.trash_entry Source: https://context7.com/libkeepass/pykeepass/llms.txt Sends an entry to the database's Recycle Bin group. Raises `UnableToSendToRecycleBin` if the entry is already in the bin. ```APIDOC ## PyKeePass.trash_entry — Move an entry to the Recycle Bin Sends an entry to the database's Recycle Bin group (created automatically if it doesn't exist). Raises `UnableToSendToRecycleBin` if the entry is already in the bin. ### Parameters - **entry**: The entry object to move to the recycle bin. ### Request Example ```python from pykeepass import PyKeePass from pykeepass.exceptions import UnableToSendToRecycleBin kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='OldService', first=True) try: kp.trash_entry(entry) print("Moved to:", kp.recyclebin_group) # Group: "Recycle Bin" except UnableToSendToRecycleBin: print("Entry is already in the recycle bin") kp.save() ``` ``` -------------------------------- ### Entry properties — Read and write entry fields Source: https://context7.com/libkeepass/pykeepass/llms.txt Provides access to standard KeePass entry fields (like title, username, password, URL, notes, tags, etc.) as read/write properties on `Entry` objects. Also covers managing timestamps, expiry, and autotype settings. ```APIDOC ## Entry properties — Read and write entry fields All standard KeePass fields are exposed as read/write properties on `Entry` objects. ```python from pykeepass import PyKeePass from datetime import datetime, timezone kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='Gmail', first=True) # Read standard fields print(entry.title) # 'Gmail' print(entry.username) # 'user@gmail.com' print(entry.password) # 'g0ogleP@ss!' print(entry.url) # 'https://mail.google.com' print(entry.notes) # 'Personal Google account' print(entry.tags) # ['personal', 'email'] print(entry.otp) # 'otpauth://totp/...' print(entry.icon) # '19' (EMail icon) print(entry.uuid) # UUID('...') print(entry.path) # ['social', 'Gmail'] print(entry.group) # Group: "social" # Write standard fields entry.title = 'Gmail (Personal)' entry.password = 'newStr0ngP@ss!' entry.notes = 'Updated 2025' entry.tags = ['personal', 'email', 'google'] entry.url = 'https://mail.google.com' # Timestamps print(entry.ctime) # datetime(2023, 1, 1, tzinfo=timezone.utc) print(entry.mtime) # last modification time print(entry.atime) # last access time entry.ctime = datetime(2024, 6, 1, tzinfo=timezone.utc) entry.touch(modify=True) # updates atime and mtime to now # Expiry entry.expires = True entry.expiry_time = datetime(2025, 12, 31, tzinfo=timezone.utc) print(entry.expired) # False (if today < 2025-12-31) # Autotype print(entry.autotype_enabled) # True print(entry.autotype_sequence) # '{USERNAME}{TAB}{PASSWORD}{ENTER}' print(entry.autotype_window) # 'Gmail - *' entry.autotype_sequence = '{USERNAME}{TAB}{PASSWORD}{ENTER}' entry.autotype_window = 'Gmail*' kp.save() ``` ``` -------------------------------- ### PyKeePass.save Source: https://context7.com/libkeepass/pykeepass/llms.txt Saves the current state of the database. Uses a safe write strategy: writes to a .tmp file first, then replaces the target file atomically. Can save to a different path or a writable stream without changing PyKeePass.filename. ```APIDOC ## `PyKeePass.save` — Save the database to disk Saves the current state of the database. Uses a safe write strategy: writes to a `.tmp` file first, then replaces the target file atomically. Can save to a different path or a writable stream without changing `PyKeePass.filename`. ```python from pykeepass import PyKeePass lp = PyKeePass('vault.kdbx', password='pass') lp.add_entry(lp.root_group, 'GitHub', 'user@example.com', 'gh_p@ssw0rd!') # Save back to the original file lp.save() # Save to a different path lp.save('vault_backup.kdbx') # Save to an in-memory stream import io stream = io.BytesIO() lp.save(stream) stream.seek(0) print(len(stream.read()), "bytes written") ``` ``` -------------------------------- ### `PyKeePass.xml` and `PyKeePass.dump_xml` — Export database as XML Source: https://context7.com/libkeepass/pykeepass/llms.txt Provides methods to access or dump the raw decrypted XML of the database, useful for inspection or backup purposes. ```APIDOC ## `PyKeePass.xml` and `PyKeePass.dump_xml` — Export database as XML Access or dump the raw decrypted XML of the database for inspection or backup purposes. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') # Get XML as bytes xml_bytes = kp.xml() print(xml_bytes[:200]) # b"\n..." # Dump XML to file kp.dump_xml('vault_export.xml') ``` ``` -------------------------------- ### Create and dereference field references between entries Source: https://context7.com/libkeepass/pykeepass/llms.txt Generate and use KeePass field reference strings (`{REF:...}`) to link fields (like passwords) between entries. Dereferencing retrieves the actual value. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') source = kp.find_entries(title='MasterAccount', first=True) target = kp.find_entries(title='DerivedService', first=True) # Generate a field reference string pointing to source's password ref_str = source.ref('password') print(ref_str) # '{REF:P@I:ABCDEF1234567890...}' # Set another entry's password to this reference target.password = ref_str # Dereference to get the actual value print(kp.deref(target.password)) # resolves to source.password value # Dereference directly on entry print(target.deref('password')) # same result kp.save() ``` -------------------------------- ### Generate OTP codes from KeePass entries Source: https://github.com/libkeepass/pykeepass/blob/master/README.md Find an entry that has an OTP attribute and use the pyotp library to parse the URI and generate the current OTP code. ```python # find an entry which has otp attribute >>> e = kp.find_entries(otp='.*', regex=True, first=True) >>> import pyotp >>> pyotp.parse_uri(e.otp).now() 799270 ``` -------------------------------- ### Move Entry in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Illustrates how to relocate an existing entry to a different group within the KeePass database. Remember to save the database to persist the move. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='Gmail', first=True) archive_group = kp.find_groups(name='archive', first=True) kp.move_entry(entry, archive_group) print(entry.path) # ['archive', 'Gmail'] kp.save() ``` -------------------------------- ### Save and manage entry version history Source: https://context7.com/libkeepass/pykeepass/llms.txt Utilize KeePass's entry version history feature. History must be explicitly saved before modifications, and individual history items or all history can be cleared. ```python from pykeepass import PyKeePass kp = PyKeePass('vault.kdbx', password='pass') entry = kp.find_entries(title='GitHub', first=True) # Save current state to history before modifying entry.save_history() # Modify the entry entry.password = 'updatedP@ss2025!' kp.save() # Inspect history for h in entry.history: print(h, h.mtime) # Delete a specific history item old = entry.history[0] entry.delete_history(old) # Clear all history entry.delete_history(all=True) kp.save() ``` -------------------------------- ### Find Entries in PyKeePass Source: https://context7.com/libkeepass/pykeepass/llms.txt Demonstrates various methods for finding entries within a KeePass database, including by group, custom fields, tags, UUID, OTP configuration, history, and path. ```python social_group = kp.find_groups(name='social', first=True) entry = kp.find_entries(title='Twitter', group=social_group, recursive=False, first=True) ``` ```python entry = kp.find_entries(string={'AccountID': '12345'}, first=True) ``` ```python entries = kp.find_entries(tags=['work', 'vpn']) ``` ```python entry = kp.find_entries(uuid=uuid.UUID('12345678-1234-5678-1234-567812345678'), first=True) ``` ```python otp_entries = kp.find_entries(otp='.*', regex=True) ``` ```python all_versions = kp.find_entries(title='Gmail', history=True) ``` ```python entry = kp.find_entries(path=['social', 'facebook']) print(entry) # Entry: "social/facebook (myusername)" ```