blob: 1d65dbeb895bf43091e86b50958c279458f237e1 [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
Guido van Rossum1e1cfa31999-05-03 18:10:37 +00005import 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:
28 raise IOError("Could not find .netrc: $HOME is not set")
Eric S. Raymond5e70cfe2000-07-13 13:25:07 +000029 fp = open(file)
Guido van Rossum9c30c241998-12-22 05:19:29 +000030 self.hosts = {}
31 self.macros = {}
32 lexer = shlex.shlex(fp)
Raymond Hettinger6eca3582003-04-23 18:59:54 +000033 lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
Guido van Rossum9c30c241998-12-22 05:19:29 +000034 while 1:
35 # Look for a machine, default, or macdef top-level keyword
36 toplevel = tt = lexer.get_token()
Fred Drake8152d322000-12-12 23:20:45 +000037 if not tt:
Guido van Rossum9c30c241998-12-22 05:19:29 +000038 break
39 elif tt == 'machine':
40 entryname = lexer.get_token()
41 elif tt == 'default':
42 entryname = 'default'
Tim Peters2344fae2001-01-15 00:50:52 +000043 elif tt == 'macdef': # Just skip to end of macdefs
Guido van Rossum9c30c241998-12-22 05:19:29 +000044 entryname = lexer.get_token()
45 self.macros[entryname] = []
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000046 lexer.whitespace = ' \t'
Guido van Rossum9c30c241998-12-22 05:19:29 +000047 while 1:
48 line = lexer.instream.readline()
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000049 if not line or line == '\012':
50 lexer.whitespace = ' \t\r\n'
Guido van Rossum9c30c241998-12-22 05:19:29 +000051 break
Guido van Rossum9c30c241998-12-22 05:19:29 +000052 self.macros[entryname].append(line)
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000053 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000054 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000055 raise NetrcParseError(
56 "bad toplevel token %r" % tt, file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000057
58 # We're looking at start of an entry for a named machine or default.
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000059 login = account = password = None
60 self.hosts[entryname] = {}
Guido van Rossum9c30c241998-12-22 05:19:29 +000061 while 1:
62 tt = lexer.get_token()
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000063 if (tt=='' or tt == 'machine' or
64 tt == 'default' or tt =='macdef'):
65 if login and password:
Guido van Rossum9c30c241998-12-22 05:19:29 +000066 self.hosts[entryname] = (login, account, password)
67 lexer.push_token(tt)
68 break
69 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000070 raise NetrcParseError(
71 "malformed %s entry %s terminated by %s"
72 % (toplevel, entryname, repr(tt)),
73 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000074 elif tt == 'login' or tt == 'user':
75 login = lexer.get_token()
76 elif tt == 'account':
77 account = lexer.get_token()
78 elif tt == 'password':
79 password = lexer.get_token()
80 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000081 raise NetrcParseError("bad follower token %r" % tt,
82 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000083
84 def authenticators(self, host):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000085 """Return a (user, account, password) tuple for given host."""
Raymond Hettinger54f02222002-06-01 14:18:47 +000086 if host in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +000087 return self.hosts[host]
Raymond Hettinger54f02222002-06-01 14:18:47 +000088 elif 'default' in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +000089 return self.hosts['default']
90 else:
91 return None
92
93 def __repr__(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000094 """Dump the class data in the format of a .netrc file."""
Guido van Rossum9c30c241998-12-22 05:19:29 +000095 rep = ""
96 for host in self.hosts.keys():
97 attrs = self.hosts[host]
98 rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
99 if attrs[1]:
100 rep = rep + "account " + repr(attrs[1])
101 rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
102 for macro in self.macros.keys():
103 rep = rep + "macdef " + macro + "\n"
104 for line in self.macros[macro]:
105 rep = rep + line
106 rep = rep + "\n"
107 return rep
108
Tim Peters2344fae2001-01-15 00:50:52 +0000109if __name__ == '__main__':
Guido van Rossum9c30c241998-12-22 05:19:29 +0000110 print netrc()