blob: 7fe69ee45874e9276c2d45d403cac146039004fc [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""An object-oriented interface to .netrc files."""
2
Tim Peters2344fae2001-01-15 00:50:52 +00003# Module and documentation by Eric S. Raymond, 21 Dec 1998
Guido van Rossum9c30c241998-12-22 05:19:29 +00004
Benjamin Peterson1df0f212011-06-10 11:32:52 -05005import io, os, shlex
Guido van Rossum9c30c241998-12-22 05:19:29 +00006
Fred Drakeec6ec902001-03-06 06:33:08 +00007__all__ = ["netrc", "NetrcParseError"]
8
9
10class NetrcParseError(Exception):
11 """Exception raised on syntax errors in the .netrc file."""
12 def __init__(self, msg, filename=None, lineno=None):
Guido van Rossum815bee42001-04-15 12:51:42 +000013 self.filename = filename
Fred Drakeec6ec902001-03-06 06:33:08 +000014 self.lineno = lineno
15 self.msg = msg
16 Exception.__init__(self, msg)
17
18 def __str__(self):
19 return "%s (%s, line %s)" % (self.msg, self.filename, self.lineno)
20
Skip Montanaro269b83b2001-02-06 01:07:02 +000021
Guido van Rossum9c30c241998-12-22 05:19:29 +000022class netrc:
23 def __init__(self, file=None):
Raymond Hettinger16e3c422002-06-01 16:07:16 +000024 if file is None:
Paul Prescodb845f3b2002-03-18 02:13:48 +000025 try:
26 file = os.path.join(os.environ['HOME'], ".netrc")
27 except KeyError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020028 raise OSError("Could not find .netrc: $HOME is not set")
Guido van Rossum9c30c241998-12-22 05:19:29 +000029 self.hosts = {}
30 self.macros = {}
Guido van Rossumc12a8132007-10-26 04:29:23 +000031 with open(file) as fp:
32 self._parse(file, fp)
33
34 def _parse(self, file, fp):
Guido van Rossum9c30c241998-12-22 05:19:29 +000035 lexer = shlex.shlex(fp)
Raymond Hettinger6eca3582003-04-23 18:59:54 +000036 lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
R. David Murray78a1a152010-12-02 03:10:43 +000037 lexer.commenters = lexer.commenters.replace('#', '')
Guido van Rossum9c30c241998-12-22 05:19:29 +000038 while 1:
39 # Look for a machine, default, or macdef top-level keyword
Benjamin Peterson1df0f212011-06-10 11:32:52 -050040 saved_lineno = lexer.lineno
Guido van Rossum9c30c241998-12-22 05:19:29 +000041 toplevel = tt = lexer.get_token()
Fred Drake8152d322000-12-12 23:20:45 +000042 if not tt:
Guido van Rossum9c30c241998-12-22 05:19:29 +000043 break
R. David Murray78a1a152010-12-02 03:10:43 +000044 elif tt[0] == '#':
Benjamin Peterson1df0f212011-06-10 11:32:52 -050045 if lexer.lineno == saved_lineno and len(tt) == 1:
46 lexer.instream.readline()
47 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000048 elif tt == 'machine':
49 entryname = lexer.get_token()
50 elif tt == 'default':
51 entryname = 'default'
Tim Peters2344fae2001-01-15 00:50:52 +000052 elif tt == 'macdef': # Just skip to end of macdefs
Guido van Rossum9c30c241998-12-22 05:19:29 +000053 entryname = lexer.get_token()
54 self.macros[entryname] = []
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000055 lexer.whitespace = ' \t'
Guido van Rossum9c30c241998-12-22 05:19:29 +000056 while 1:
57 line = lexer.instream.readline()
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000058 if not line or line == '\012':
59 lexer.whitespace = ' \t\r\n'
Guido van Rossum9c30c241998-12-22 05:19:29 +000060 break
Guido van Rossum9c30c241998-12-22 05:19:29 +000061 self.macros[entryname].append(line)
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000062 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000063 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000064 raise NetrcParseError(
65 "bad toplevel token %r" % tt, file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000066
67 # We're looking at start of an entry for a named machine or default.
Raymond Hettingerb34ef942003-04-24 20:11:20 +000068 login = ''
69 account = password = None
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000070 self.hosts[entryname] = {}
Guido van Rossum9c30c241998-12-22 05:19:29 +000071 while 1:
72 tt = lexer.get_token()
Benjamin Peterson1df0f212011-06-10 11:32:52 -050073 if (tt.startswith('#') or
74 tt in {'', 'machine', 'default', 'macdef'}):
Raymond Hettingerb34ef942003-04-24 20:11:20 +000075 if password:
Guido van Rossum9c30c241998-12-22 05:19:29 +000076 self.hosts[entryname] = (login, account, password)
77 lexer.push_token(tt)
78 break
79 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000080 raise NetrcParseError(
81 "malformed %s entry %s terminated by %s"
82 % (toplevel, entryname, repr(tt)),
83 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000084 elif tt == 'login' or tt == 'user':
85 login = lexer.get_token()
86 elif tt == 'account':
87 account = lexer.get_token()
88 elif tt == 'password':
89 password = lexer.get_token()
90 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000091 raise NetrcParseError("bad follower token %r" % tt,
92 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000093
94 def authenticators(self, host):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000095 """Return a (user, account, password) tuple for given host."""
Raymond Hettinger54f02222002-06-01 14:18:47 +000096 if host in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +000097 return self.hosts[host]
Raymond Hettinger54f02222002-06-01 14:18:47 +000098 elif 'default' in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +000099 return self.hosts['default']
100 else:
101 return None
102
103 def __repr__(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000104 """Dump the class data in the format of a .netrc file."""
Guido van Rossum9c30c241998-12-22 05:19:29 +0000105 rep = ""
106 for host in self.hosts.keys():
107 attrs = self.hosts[host]
108 rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
109 if attrs[1]:
110 rep = rep + "account " + repr(attrs[1])
111 rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
112 for macro in self.macros.keys():
113 rep = rep + "macdef " + macro + "\n"
114 for line in self.macros[macro]:
115 rep = rep + line
116 rep = rep + "\n"
117 return rep
118
Tim Peters2344fae2001-01-15 00:50:52 +0000119if __name__ == '__main__':
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 print(netrc())