keepass.py 1.0 KB

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