keepass.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import subprocess
  2. from pathlib import Path
  3. from dataclasses import dataclass
  4. from typing import Any
  5. from pc_backup.env import is_windows
  6. @dataclass
  7. class KeePass:
  8. path: Path
  9. bin: str | Path
  10. def read_entry_attribute(self, key, attribute):
  11. print(f"reading attr {attribute} of key {key}..")
  12. return self._exec(["show", "-a", attribute, self.path, key]).strip()
  13. def read_entry_attachment(self, key, attachment):
  14. print(f"reading attachment {attachment} of key {key}..")
  15. return self._exec(
  16. ["attachment-export", "--stdout", self.path, key, attachment, "/dev/null"]
  17. )
  18. def _exec(self, args: list[Any]):
  19. try:
  20. return subprocess.check_output([self.bin] + args, text=True)
  21. except subprocess.CalledProcessError as e:
  22. print("\nThere was an error on call to keepass, please check the outout")
  23. exit(1)
  24. @classmethod
  25. def new(cls, path: Path):
  26. binary = (
  27. Path("C:\\") / "Program Files" / "KeePassXC" / "keepassxc-cli.exe"
  28. if is_windows()
  29. else "keepassxc-cli"
  30. )
  31. return cls(path=path, bin=binary)