You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

getnetrc 1.1KB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python
  2. #
  3. # pbrisbin 2013 - retreive passwords by email address from ~/.netrc.
  4. # Unlike typical netrc usage, this allows you to store credentials under
  5. # the domain of the email address, rather than the hostname of the IMAP
  6. # server (which may be the same for multiple sets of credentials).
  7. #
  8. # Example ~/.netrc:
  9. #
  10. # machine gmail.com
  11. # login pbrisbin@gmail.com
  12. # password supersecret
  13. #
  14. # machine thoughtbot.com
  15. # login pat@thoughtbot.com
  16. # password othersecret
  17. #
  18. # Usage:
  19. #
  20. # $ getnetrc pbrisbin@gmail.com
  21. # supersecret
  22. #
  23. # $ getnetrc pat@thoughtbot.com
  24. # othersecret
  25. #
  26. ###
  27. import netrc
  28. import sys
  29. def get_password(email_address):
  30. try:
  31. net_rc = netrc.netrc()
  32. except IOError:
  33. return None
  34. try:
  35. domain = email_address.split('@', 2)[1]
  36. except:
  37. return None
  38. for host in net_rc.hosts.keys():
  39. if host == domain:
  40. login, _, password = net_rc.authenticators(host)
  41. if login == email_address:
  42. return password
  43. return None
  44. if __name__ == '__main__':
  45. pw = get_password(sys.argv[1])
  46. if pw: print(pw)