netrc.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """An object-oriented interface to .netrc files."""
  2. # Module and documentation by Eric S. Raymond, 21 Dec 1998
  3. import os, shlex, stat
  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. default_netrc = file is None
  17. if file is None:
  18. try:
  19. file = os.path.join(os.environ['HOME'], ".netrc")
  20. except KeyError:
  21. raise OSError("Could not find .netrc: $HOME is not set")
  22. self.hosts = {}
  23. self.macros = {}
  24. with open(file) as fp:
  25. self._parse(file, fp, default_netrc)
  26. def _parse(self, file, fp, default_netrc):
  27. lexer = shlex.shlex(fp)
  28. lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  29. lexer.commenters = lexer.commenters.replace('#', '')
  30. while 1:
  31. # Look for a machine, default, or macdef top-level keyword
  32. saved_lineno = lexer.lineno
  33. toplevel = tt = lexer.get_token()
  34. if not tt:
  35. break
  36. elif tt[0] == '#':
  37. if lexer.lineno == saved_lineno and len(tt) == 1:
  38. lexer.instream.readline()
  39. continue
  40. elif tt == 'machine':
  41. entryname = lexer.get_token()
  42. elif tt == 'default':
  43. entryname = 'default'
  44. elif tt == 'macdef': # Just skip to end of macdefs
  45. entryname = lexer.get_token()
  46. self.macros[entryname] = []
  47. lexer.whitespace = ' \t'
  48. while 1:
  49. line = lexer.instream.readline()
  50. if not line or line == '\012':
  51. lexer.whitespace = ' \t\r\n'
  52. break
  53. self.macros[entryname].append(line)
  54. continue
  55. else:
  56. raise NetrcParseError(
  57. "bad toplevel token %r" % tt, file, lexer.lineno)
  58. # We're looking at start of an entry for a named machine or default.
  59. login = ''
  60. account = password = None
  61. self.hosts[entryname] = {}
  62. while 1:
  63. tt = lexer.get_token()
  64. if (tt.startswith('#') or
  65. tt in {'', 'machine', 'default', 'macdef'}):
  66. if password:
  67. self.hosts[entryname] = (login, account, password)
  68. lexer.push_token(tt)
  69. break
  70. else:
  71. raise NetrcParseError(
  72. "malformed %s entry %s terminated by %s"
  73. % (toplevel, entryname, repr(tt)),
  74. file, lexer.lineno)
  75. elif tt == 'login' or tt == 'user':
  76. login = lexer.get_token()
  77. elif tt == 'account':
  78. account = lexer.get_token()
  79. elif tt == 'password':
  80. if os.name == 'posix' and default_netrc:
  81. prop = os.fstat(fp.fileno())
  82. if prop.st_uid != os.getuid():
  83. import pwd
  84. try:
  85. fowner = pwd.getpwuid(prop.st_uid)[0]
  86. except KeyError:
  87. fowner = 'uid %s' % prop.st_uid
  88. try:
  89. user = pwd.getpwuid(os.getuid())[0]
  90. except KeyError:
  91. user = 'uid %s' % os.getuid()
  92. raise NetrcParseError(
  93. ("~/.netrc file owner (%s) does not match"
  94. " current user (%s)") % (fowner, user),
  95. file, lexer.lineno)
  96. if (prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO)):
  97. raise NetrcParseError(
  98. "~/.netrc access too permissive: access"
  99. " permissions must restrict access to only"
  100. " the owner", file, lexer.lineno)
  101. password = lexer.get_token()
  102. else:
  103. raise NetrcParseError("bad follower token %r" % tt,
  104. file, lexer.lineno)
  105. def authenticators(self, host):
  106. """Return a (user, account, password) tuple for given host."""
  107. if host in self.hosts:
  108. return self.hosts[host]
  109. elif 'default' in self.hosts:
  110. return self.hosts['default']
  111. else:
  112. return None
  113. def __repr__(self):
  114. """Dump the class data in the format of a .netrc file."""
  115. rep = ""
  116. for host in self.hosts.keys():
  117. attrs = self.hosts[host]
  118. rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
  119. if attrs[1]:
  120. rep = rep + "account " + repr(attrs[1])
  121. rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
  122. for macro in self.macros.keys():
  123. rep = rep + "macdef " + macro + "\n"
  124. for line in self.macros[macro]:
  125. rep = rep + line
  126. rep = rep + "\n"
  127. return rep
  128. if __name__ == '__main__':
  129. print(netrc())