change_passphrase.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. import borgmatic.config.paths
  3. import borgmatic.execute
  4. import borgmatic.logger
  5. from borgmatic.borg import environment, flags
  6. logger = logging.getLogger(__name__)
  7. def change_passphrase(
  8. repository_path,
  9. config,
  10. local_borg_version,
  11. change_passphrase_arguments,
  12. global_arguments,
  13. local_path='borg',
  14. remote_path=None,
  15. ):
  16. '''
  17. Given a local or remote repository path, a configuration dict, the local Borg version, change
  18. passphrase arguments, and optional local and remote Borg paths, change the repository passphrase
  19. based on an interactive prompt.
  20. '''
  21. borgmatic.logger.add_custom_log_levels()
  22. umask = config.get('umask', None)
  23. lock_wait = config.get('lock_wait', None)
  24. full_command = (
  25. (local_path, 'key', 'change-passphrase')
  26. + (('--remote-path', remote_path) if remote_path else ())
  27. + (('--umask', str(umask)) if umask else ())
  28. + (('--log-json',) if config.get('log_json') else ())
  29. + (('--lock-wait', str(lock_wait)) if lock_wait else ())
  30. + (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
  31. + (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ())
  32. + flags.make_repository_flags(
  33. repository_path,
  34. local_borg_version,
  35. )
  36. )
  37. if global_arguments.dry_run:
  38. logger.info('Skipping change password (dry run)')
  39. return
  40. # If the original passphrase is set programmatically, then Borg won't prompt for a new one! So
  41. # don't give Borg any passphrase, and it'll ask the user for both old and new ones.
  42. config_without_passphrase = {
  43. option_name: value
  44. for (option_name, value) in config.items()
  45. if option_name not in {'encryption_passphrase', 'encryption_passcommand'}
  46. }
  47. borgmatic.execute.execute_command(
  48. full_command,
  49. output_file=borgmatic.execute.DO_NOT_CAPTURE,
  50. output_log_level=logging.ANSWER,
  51. environment=environment.make_environment(config_without_passphrase),
  52. working_directory=borgmatic.config.paths.get_working_directory(config),
  53. borg_local_path=local_path,
  54. borg_exit_codes=config.get('borg_exit_codes'),
  55. )
  56. logger.answer(
  57. f"{repository_path}: Don't forget to update your encryption_passphrase option (if needed)",
  58. )