1 """An object-oriented interface to .netrc files."""
3 # Module and documentation by Eric S. Raymond, 21 Dec 1998
7 __all__
= ["netrc", "NetrcParseError"]
10 class NetrcParseError(Exception):
11 """Exception raised on syntax errors in the .netrc file."""
12 def __init__(self
, msg
, filename
=None, lineno
=None):
13 self
.filename
= filename
16 Exception.__init
__(self
, msg
)
19 return "%s (%s, line %s)" % (self
.msg
, self
.filename
, self
.lineno
)
23 def __init__(self
, file=None):
26 file = os
.path
.join(os
.environ
['HOME'], ".netrc")
28 raise IOError("Could not find .netrc: $HOME is not set")
32 lexer
= shlex
.shlex(fp
)
33 lexer
.wordchars
+= r
"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
35 # Look for a machine, default, or macdef top-level keyword
36 toplevel
= tt
= lexer
.get_token()
40 entryname
= lexer
.get_token()
43 elif tt
== 'macdef': # Just skip to end of macdefs
44 entryname
= lexer
.get_token()
45 self
.macros
[entryname
] = []
46 lexer
.whitespace
= ' \t'
48 line
= lexer
.instream
.readline()
49 if not line
or line
== '\012':
50 lexer
.whitespace
= ' \t\r\n'
52 self
.macros
[entryname
].append(line
)
55 raise NetrcParseError(
56 "bad toplevel token %r" % tt
, file, lexer
.lineno
)
58 # We're looking at start of an entry for a named machine or default.
60 account
= password
= None
61 self
.hosts
[entryname
] = {}
63 tt
= lexer
.get_token()
64 if (tt
=='' or tt
== 'machine' or
65 tt
== 'default' or tt
=='macdef'):
67 self
.hosts
[entryname
] = (login
, account
, password
)
71 raise NetrcParseError(
72 "malformed %s entry %s terminated by %s"
73 % (toplevel
, entryname
, repr(tt
)),
75 elif tt
== 'login' or tt
== 'user':
76 login
= lexer
.get_token()
78 account
= lexer
.get_token()
79 elif tt
== 'password':
80 password
= lexer
.get_token()
82 raise NetrcParseError("bad follower token %r" % tt
,
85 def authenticators(self
, host
):
86 """Return a (user, account, password) tuple for given host."""
87 if host
in self
.hosts
:
88 return self
.hosts
[host
]
89 elif 'default' in self
.hosts
:
90 return self
.hosts
['default']
95 """Dump the class data in the format of a .netrc file."""
97 for host
in self
.hosts
.keys():
98 attrs
= self
.hosts
[host
]
99 rep
= rep
+ "machine "+ host
+ "\n\tlogin " + repr(attrs
[0]) + "\n"
101 rep
= rep
+ "account " + repr(attrs
[1])
102 rep
= rep
+ "\tpassword " + repr(attrs
[2]) + "\n"
103 for macro
in self
.macros
.keys():
104 rep
= rep
+ "macdef " + macro
+ "\n"
105 for line
in self
.macros
[macro
]:
110 if __name__
== '__main__':