getnetrc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. # thcipriani <tyler@tylercipriani.com> 2014
  27. # Updated to also retrieve usernames when evaluated as a script.
  28. # Also, checks for '@' sign for get_password, only checks mail if
  29. # that exists
  30. #
  31. ###
  32. import netrc
  33. import sys
  34. def get_password(domain_or_email):
  35. try:
  36. net_rc = netrc.netrc()
  37. except IOError:
  38. return None
  39. if "@" in domain_or_email:
  40. domain = domain_or_email.split('@', 2)[1]
  41. email = domain_or_email
  42. else:
  43. domain = domain_or_email
  44. for host in net_rc.hosts.keys():
  45. if host == domain:
  46. login, _, password = net_rc.authenticators(host)
  47. try:
  48. if email != login:
  49. continue;
  50. except NameError:
  51. pass
  52. return password
  53. return None
  54. def get_login(domain):
  55. try:
  56. net_rc = netrc.netrc()
  57. except IOError:
  58. return None
  59. for host in net_rc.hosts.keys():
  60. if host == domain:
  61. login, _, password = net_rc.authenticators(host)
  62. return login
  63. return None
  64. if __name__ == '__main__':
  65. if len(sys.argv) > 2 and sys.argv[2] == 'login':
  66. pw = get_login(sys.argv[1])
  67. else:
  68. pw = get_password(sys.argv[1])
  69. if pw:
  70. print(pw)