blob: bbb3d23b5433433ec89c07dfb6a7ddbd5027e9ec [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
R David Murray505be212013-09-18 08:52:38 -04005import os, shlex, stat
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):
R David Murray104aab92013-09-17 20:30:02 -040024 default_netrc = file is None
Raymond Hettinger16e3c422002-06-01 16:07:16 +000025 if file is None:
Paul Prescodb845f3b2002-03-18 02:13:48 +000026 try:
27 file = os.path.join(os.environ['HOME'], ".netrc")
28 except KeyError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020029 raise OSError("Could not find .netrc: $HOME is not set")
Guido van Rossum9c30c241998-12-22 05:19:29 +000030 self.hosts = {}
31 self.macros = {}
Guido van Rossumc12a8132007-10-26 04:29:23 +000032 with open(file) as fp:
R David Murray104aab92013-09-17 20:30:02 -040033 self._parse(file, fp, default_netrc)
Guido van Rossumc12a8132007-10-26 04:29:23 +000034
R David Murray104aab92013-09-17 20:30:02 -040035 def _parse(self, file, fp, default_netrc):
Guido van Rossum9c30c241998-12-22 05:19:29 +000036 lexer = shlex.shlex(fp)
Raymond Hettinger6eca3582003-04-23 18:59:54 +000037 lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
R. David Murray78a1a152010-12-02 03:10:43 +000038 lexer.commenters = lexer.commenters.replace('#', '')
Guido van Rossum9c30c241998-12-22 05:19:29 +000039 while 1:
40 # Look for a machine, default, or macdef top-level keyword
Benjamin Peterson1df0f212011-06-10 11:32:52 -050041 saved_lineno = lexer.lineno
Guido van Rossum9c30c241998-12-22 05:19:29 +000042 toplevel = tt = lexer.get_token()
Fred Drake8152d322000-12-12 23:20:45 +000043 if not tt:
Guido van Rossum9c30c241998-12-22 05:19:29 +000044 break
R. David Murray78a1a152010-12-02 03:10:43 +000045 elif tt[0] == '#':
Benjamin Peterson1df0f212011-06-10 11:32:52 -050046 if lexer.lineno == saved_lineno and len(tt) == 1:
47 lexer.instream.readline()
48 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000049 elif tt == 'machine':
50 entryname = lexer.get_token()
51 elif tt == 'default':
52 entryname = 'default'
Tim Peters2344fae2001-01-15 00:50:52 +000053 elif tt == 'macdef': # Just skip to end of macdefs
Guido van Rossum9c30c241998-12-22 05:19:29 +000054 entryname = lexer.get_token()
55 self.macros[entryname] = []
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000056 lexer.whitespace = ' \t'
Guido van Rossum9c30c241998-12-22 05:19:29 +000057 while 1:
58 line = lexer.instream.readline()
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000059 if not line or line == '\012':
60 lexer.whitespace = ' \t\r\n'
Guido van Rossum9c30c241998-12-22 05:19:29 +000061 break
Guido van Rossum9c30c241998-12-22 05:19:29 +000062 self.macros[entryname].append(line)
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000063 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000064 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000065 raise NetrcParseError(
66 "bad toplevel token %r" % tt, file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000067
68 # We're looking at start of an entry for a named machine or default.
Raymond Hettingerb34ef942003-04-24 20:11:20 +000069 login = ''
70 account = password = None
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000071 self.hosts[entryname] = {}
Guido van Rossum9c30c241998-12-22 05:19:29 +000072 while 1:
73 tt = lexer.get_token()
Benjamin Peterson1df0f212011-06-10 11:32:52 -050074 if (tt.startswith('#') or
75 tt in {'', 'machine', 'default', 'macdef'}):
Raymond Hettingerb34ef942003-04-24 20:11:20 +000076 if password:
Guido van Rossum9c30c241998-12-22 05:19:29 +000077 self.hosts[entryname] = (login, account, password)
78 lexer.push_token(tt)
79 break
80 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000081 raise NetrcParseError(
82 "malformed %s entry %s terminated by %s"
83 % (toplevel, entryname, repr(tt)),
84 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000085 elif tt == 'login' or tt == 'user':
86 login = lexer.get_token()
87 elif tt == 'account':
88 account = lexer.get_token()
89 elif tt == 'password':
R David Murray104aab92013-09-17 20:30:02 -040090 if os.name == 'posix' and default_netrc:
91 prop = os.fstat(fp.fileno())
92 if prop.st_uid != os.getuid():
R David Murray6bd3e442013-09-18 08:59:47 -040093 import pwd
R David Murray104aab92013-09-17 20:30:02 -040094 try:
95 fowner = pwd.getpwuid(prop.st_uid)[0]
96 except KeyError:
97 fowner = 'uid %s' % prop.st_uid
98 try:
99 user = pwd.getpwuid(os.getuid())[0]
100 except KeyError:
101 user = 'uid %s' % os.getuid()
102 raise NetrcParseError(
103 ("~/.netrc file owner (%s) does not match"
104 " current user (%s)") % (fowner, user),
105 file, lexer.lineno)
106 if (prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO)):
107 raise NetrcParseError(
108 "~/.netrc access too permissive: access"
109 " permissions must restrict access to only"
110 " the owner", file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000111 password = lexer.get_token()
112 else:
Fred Drakeec6ec902001-03-06 06:33:08 +0000113 raise NetrcParseError("bad follower token %r" % tt,
114 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000115
116 def authenticators(self, host):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000117 """Return a (user, account, password) tuple for given host."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000118 if host in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000119 return self.hosts[host]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000120 elif 'default' in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000121 return self.hosts['default']
122 else:
123 return None
124
125 def __repr__(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000126 """Dump the class data in the format of a .netrc file."""
Guido van Rossum9c30c241998-12-22 05:19:29 +0000127 rep = ""
128 for host in self.hosts.keys():
129 attrs = self.hosts[host]
130 rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n"
131 if attrs[1]:
132 rep = rep + "account " + repr(attrs[1])
133 rep = rep + "\tpassword " + repr(attrs[2]) + "\n"
134 for macro in self.macros.keys():
135 rep = rep + "macdef " + macro + "\n"
136 for line in self.macros[macro]:
137 rep = rep + line
138 rep = rep + "\n"
139 return rep
140
Tim Peters2344fae2001-01-15 00:50:52 +0000141if __name__ == '__main__':
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000142 print(netrc())