hash_password 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python
  2. import argparse
  3. import getpass
  4. import sys
  5. import bcrypt
  6. import yaml
  7. bcrypt_rounds=12
  8. password_pepper = ""
  9. def prompt_for_pass():
  10. password = getpass.getpass("Password: ")
  11. if not password:
  12. raise Exception("Password cannot be blank.")
  13. confirm_password = getpass.getpass("Confirm password: ")
  14. if password != confirm_password:
  15. raise Exception("Passwords do not match.")
  16. return password
  17. if __name__ == "__main__":
  18. parser = argparse.ArgumentParser(
  19. description="Calculate the hash of a new password, so that passwords"
  20. " can be reset")
  21. parser.add_argument(
  22. "-p", "--password",
  23. default=None,
  24. help="New password for user. Will prompt if omitted.",
  25. )
  26. parser.add_argument(
  27. "-c", "--config",
  28. type=argparse.FileType('r'),
  29. help="Path to server config file. Used to read in bcrypt_rounds and password_pepper.",
  30. )
  31. args = parser.parse_args()
  32. if "config" in args and args.config:
  33. config = yaml.safe_load(args.config)
  34. bcrypt_rounds = config.get("bcrypt_rounds", bcrypt_rounds)
  35. password_config = config.get("password_config", {})
  36. password_pepper = password_config.get("pepper", password_pepper)
  37. password = args.password
  38. if not password:
  39. password = prompt_for_pass()
  40. print bcrypt.hashpw(password + password_pepper, bcrypt.gensalt(bcrypt_rounds))