netrc.py 5.4 KB

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