db_interactor/keepass.py
Frederik Jacobsen 8f736f58f3 Added a way to run the same query on multiple schemas and logging.
Need to work on running update queries, that combine plsql and normal sql statements and potentially multiple extracts for one sql file, to make multiple files, and probably to also export to xlsx file format.
2024-12-12 21:50:37 +01:00

53 lines
2.1 KiB
Python

import logging
from pykeepass import PyKeePass
from config import KeePassConfig
import getpass
from dataclasses import dataclass
@dataclass
class KeePassEntry:
def __init__(self, name: str, password: str):
self._name = name
self._password = password
@property
def password(self) -> str:
return self._password
@property
def name(self) -> str:
return self._name
class KeePass:
def __init__(self, config: KeePassConfig, logger: logging.Logger):
self._logger: logging.Logger = logger
self._kee_pass_config: KeePassConfig = config
self._password: str = getpass.getpass(f'KeePass password for {config.path}: ')
self._logger.info(f'Initializing connection to keepass file {config.path}')
self._kee_pass: PyKeePass = PyKeePass(config.path, password=self._password)
self._logger.info(f'Successfully connected to keepass')
def get_db_credentials(self) -> KeePassEntry:
self._logger.info(f'Searching for database credentials on credential: {self._kee_pass_config.db_credentials_name}')
group = self._kee_pass
if self._kee_pass_config.db_credentials_group.strip() is not None and self._kee_pass_config.db_credentials_group.strip() != "":
self._logger.info(f'Searching in group {self._kee_pass_config.db_credentials_group}')
group = self._kee_pass.find_entries(name=self._kee_pass_config.db_credentials_name)
else:
self._logger.info('Searching in root')
group = group.find_entries(title=self._kee_pass_config.db_credentials_name)
if group is None:
self._logger.critical(f'Group {self._kee_pass_config.db_credentials_group} not found')
raise Exception(f'Group {self._kee_pass_config.db_credentials_group} not found')
if len(group) != 1:
self._logger.critical(f'Could not find password, found {len(group)} entries')
raise Exception(f'Could not find password, found {len(group)} entries')
self._logger.info(f'Found credentials for database for username {group[0].username}')
return KeePassEntry(group[0].username, group[0].password)