netrc.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """An object-oriented interface to .netrc files."""
  2. # Module and documentation by Eric S. Raymond, 21 Dec 1998
  3. import os, shlex
  4. __all__ = ["netrc", "NetrcParseError"]
  5. class NetrcParseError(Exception):
  6. """Exception raised on syntax errors in the .netrc file."""
  7. def __init__(self, msg, filename=None, lineno=None):
  8. self.filename = filename
  9. self.lineno = lineno
  10. self.msg = msg
  11. Exception.__init__(self, msg)
  12. def __str__(self):
  13. return "%s (%s, line %s)" % (self.msg, self.filename, self.lineno)
  14. class netrc:
  15. def __init__(self, file=None):
  16. if file is None:
  17. try:
  18. file = os.path.join(os.environ['HOME'], ".netrc")
  19. except KeyError:
  20. raise IOError("Could not find .netrc: $HOME is not set")
  21. fp = open(file)
  22. self.hosts = {}
  23. self.macros = {}
  24. lexer = shlex.shlex(fp)
  25. lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  26. while 1:
  27. # Look for a machine, default, or macdef top-level keyword
  28. toplevel = tt = lexer.get_token()
  29. if not tt:
  30. break
  31. elif tt == 'machine':
  32. entryname = lexer.get_token()
  33. elif tt == 'default':
  34. entryname = 'default'
  35. elif tt == 'macdef': # Just skip to end of macdefs
  36. entryname = lexer.get_token()
  37. self.macros[entryname] = []
  38. lexer.whitespace = ' \t'
  39. while 1:
  40. line = lexer.instream.readline()
  41. if not line or line == '\012':
  42. lexer.whitespace = ' \t\r\n'
  43. break
  44. self.macros[entryname].append(line)
  45. continue
  46. else:
  47. raise NetrcParseError(
  48. "bad toplevel token %r" % tt, file, lexer.lineno)
  49. # We're looking at start of an entry for a named machine or default.
  50. login = ''
  51. account = password = None
  52. self.hosts[entryname] = {}
  53. while 1:
  54. tt = lexer.get_token()
  55. if (tt=='' or tt == 'machine' or
  56. tt == 'default' or tt =='macdef'):
  57. if password:
  58. self.hosts[entryname] = (login, account, password)
  59. lexer.push_token(tt)
  60. break
  61. else:
  62. raise NetrcParseError(
  63. "malformed %s entry %s terminated by %s"
  64. % (toplevel, entryname, repr(tt)),
  65. file, lexer.lineno)
  66. elif tt == 'login' or tt == 'user':
  67. login = lexer.get_token()
  68. elif tt == 'account':
  69. account = lexer.get_token()
  70. elif tt == 'password':
  71. password = lexer.get_token()
  72. else:
  73. raise NetrcParseError("bad follower token %r" % tt,
  74. file, lexer.lineno)
  75. def authenticators(self, host):
  76. """Return a (user, account, password) tuple for given host."""
  77. if host in self.hosts:
  78. return self.hosts[host]
  79. elif 'default' in self.hosts:
  80. return self.hosts['default']
  81. else:
  82. return None
  83. def __repr__(self):
  84. """Dump the class data in the format of a .netrc file."""
  85. rep = ""
  86. for host in self.hosts.keys():
  87. attrs = self.hosts[host]
  88. rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
  89. if attrs[1]:
  90. rep = rep + "account " + repr(attrs[1])
  91. rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
  92. for macro in self.macros.keys():
  93. rep = rep + "macdef " + macro + "\n"
  94. for line in self.macros[macro]:
  95. rep = rep + line
  96. rep = rep + "\n"
  97. return rep
  98. if __name__ == '__main__':
  99. print netrc()