"""An object-oriented interface to .netrc files."""
# Module and documentation by Eric S. Raymond, 21 Dec 1998
__all__ = ["netrc", "NetrcParseError"]
class NetrcParseError(Exception):
"""Exception raised on syntax errors in the .netrc file."""
def __init__(self, msg, filename=None, lineno=None):
Exception.__init__(self, msg)
return "%s (%s, line %s)" % (self.msg, self.filename, self.lineno)
def __init__(self, file=None):
default_netrc = file is None
file = os.path.join(os.environ['HOME'], ".netrc")
raise IOError("Could not find .netrc: $HOME is not set")
self._parse(file, fp, default_netrc)
def _parse(self, file, fp, default_netrc):
lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
lexer.commenters = lexer.commenters.replace('#', '')
# Look for a machine, default, or macdef top-level keyword
toplevel = tt = lexer.get_token()
# seek to beginning of comment, in case reading the token put
# us on a new line, and then skip the rest of the line.
lexer.instream.seek(-pos, 1)
lexer.instream.readline()
entryname = lexer.get_token()
elif tt == 'macdef': # Just skip to end of macdefs
entryname = lexer.get_token()
self.macros[entryname] = []
line = lexer.instream.readline()
if not line or line == '\012':
lexer.whitespace = ' \t\r\n'
self.macros[entryname].append(line)
"bad toplevel token %r" % tt, file, lexer.lineno)
# We're looking at start of an entry for a named machine or default.
account = password = None
self.hosts[entryname] = {}
if (tt.startswith('#') or
tt in {'', 'machine', 'default', 'macdef'}):
self.hosts[entryname] = (login, account, password)
"malformed %s entry %s terminated by %s"
% (toplevel, entryname, repr(tt)),
elif tt == 'login' or tt == 'user':
login = lexer.get_token()
account = lexer.get_token()
if os.name == 'posix' and default_netrc:
prop = os.fstat(fp.fileno())
if prop.st_uid != os.getuid():
fowner = pwd.getpwuid(prop.st_uid)[0]
fowner = 'uid %s' % prop.st_uid
user = pwd.getpwuid(os.getuid())[0]
user = 'uid %s' % os.getuid()
("~/.netrc file owner (%s) does not match"
" current user (%s)") % (fowner, user),
if (prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO)):
"~/.netrc access too permissive: access"
" permissions must restrict access to only"
" the owner", file, lexer.lineno)
password = lexer.get_token()
raise NetrcParseError("bad follower token %r" % tt,
def authenticators(self, host):
"""Return a (user, account, password) tuple for given host."""
elif 'default' in self.hosts:
return self.hosts['default']
"""Dump the class data in the format of a .netrc file."""
for host in self.hosts.keys():
rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
rep = rep + "account " + repr(attrs[1])
rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
for macro in self.macros.keys():
rep = rep + "macdef " + macro + "\n"
for line in self.macros[macro]:
if __name__ == '__main__':