blob: f0ae48cfed9e67e8192b82fc66c0755a8cfdb270 [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:
Berker Peksag8d9bb112017-11-25 13:37:22 +030026 file = os.path.join(os.path.expanduser("~"), ".netrc")
Guido van Rossum9c30c241998-12-22 05:19:29 +000027 self.hosts = {}
28 self.macros = {}
Guido van Rossumc12a8132007-10-26 04:29:23 +000029 with open(file) as fp:
R David Murray104aab92013-09-17 20:30:02 -040030 self._parse(file, fp, default_netrc)
Guido van Rossumc12a8132007-10-26 04:29:23 +000031
R David Murray104aab92013-09-17 20:30:02 -040032 def _parse(self, file, fp, default_netrc):
Guido van Rossum9c30c241998-12-22 05:19:29 +000033 lexer = shlex.shlex(fp)
Raymond Hettinger6eca3582003-04-23 18:59:54 +000034 lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
R. David Murray78a1a152010-12-02 03:10:43 +000035 lexer.commenters = lexer.commenters.replace('#', '')
Guido van Rossum9c30c241998-12-22 05:19:29 +000036 while 1:
37 # Look for a machine, default, or macdef top-level keyword
Benjamin Peterson1df0f212011-06-10 11:32:52 -050038 saved_lineno = lexer.lineno
Guido van Rossum9c30c241998-12-22 05:19:29 +000039 toplevel = tt = lexer.get_token()
Fred Drake8152d322000-12-12 23:20:45 +000040 if not tt:
Guido van Rossum9c30c241998-12-22 05:19:29 +000041 break
R. David Murray78a1a152010-12-02 03:10:43 +000042 elif tt[0] == '#':
Benjamin Peterson1df0f212011-06-10 11:32:52 -050043 if lexer.lineno == saved_lineno and len(tt) == 1:
44 lexer.instream.readline()
45 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000046 elif tt == 'machine':
47 entryname = lexer.get_token()
48 elif tt == 'default':
49 entryname = 'default'
Tim Peters2344fae2001-01-15 00:50:52 +000050 elif tt == 'macdef': # Just skip to end of macdefs
Guido van Rossum9c30c241998-12-22 05:19:29 +000051 entryname = lexer.get_token()
52 self.macros[entryname] = []
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000053 lexer.whitespace = ' \t'
Guido van Rossum9c30c241998-12-22 05:19:29 +000054 while 1:
55 line = lexer.instream.readline()
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000056 if not line or line == '\012':
57 lexer.whitespace = ' \t\r\n'
Guido van Rossum9c30c241998-12-22 05:19:29 +000058 break
Guido van Rossum9c30c241998-12-22 05:19:29 +000059 self.macros[entryname].append(line)
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000060 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +000061 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000062 raise NetrcParseError(
63 "bad toplevel token %r" % tt, file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000064
65 # We're looking at start of an entry for a named machine or default.
Raymond Hettingerb34ef942003-04-24 20:11:20 +000066 login = ''
67 account = password = None
Andrew M. Kuchling366a1df2002-03-22 02:46:41 +000068 self.hosts[entryname] = {}
Guido van Rossum9c30c241998-12-22 05:19:29 +000069 while 1:
70 tt = lexer.get_token()
Benjamin Peterson1df0f212011-06-10 11:32:52 -050071 if (tt.startswith('#') or
72 tt in {'', 'machine', 'default', 'macdef'}):
Raymond Hettingerb34ef942003-04-24 20:11:20 +000073 if password:
Guido van Rossum9c30c241998-12-22 05:19:29 +000074 self.hosts[entryname] = (login, account, password)
75 lexer.push_token(tt)
76 break
77 else:
Fred Drakeec6ec902001-03-06 06:33:08 +000078 raise NetrcParseError(
79 "malformed %s entry %s terminated by %s"
80 % (toplevel, entryname, repr(tt)),
81 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000082 elif tt == 'login' or tt == 'user':
83 login = lexer.get_token()
84 elif tt == 'account':
85 account = lexer.get_token()
86 elif tt == 'password':
R David Murray104aab92013-09-17 20:30:02 -040087 if os.name == 'posix' and default_netrc:
88 prop = os.fstat(fp.fileno())
89 if prop.st_uid != os.getuid():
R David Murray6bd3e442013-09-18 08:59:47 -040090 import pwd
R David Murray104aab92013-09-17 20:30:02 -040091 try:
92 fowner = pwd.getpwuid(prop.st_uid)[0]
93 except KeyError:
94 fowner = 'uid %s' % prop.st_uid
95 try:
96 user = pwd.getpwuid(os.getuid())[0]
97 except KeyError:
98 user = 'uid %s' % os.getuid()
99 raise NetrcParseError(
100 ("~/.netrc file owner (%s) does not match"
101 " current user (%s)") % (fowner, user),
102 file, lexer.lineno)
103 if (prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO)):
104 raise NetrcParseError(
105 "~/.netrc access too permissive: access"
106 " permissions must restrict access to only"
107 " the owner", file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000108 password = lexer.get_token()
109 else:
Fred Drakeec6ec902001-03-06 06:33:08 +0000110 raise NetrcParseError("bad follower token %r" % tt,
111 file, lexer.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000112
113 def authenticators(self, host):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000114 """Return a (user, account, password) tuple for given host."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000115 if host in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000116 return self.hosts[host]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000117 elif 'default' in self.hosts:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000118 return self.hosts['default']
119 else:
120 return None
121
122 def __repr__(self):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000123 """Dump the class data in the format of a .netrc file."""
Guido van Rossum9c30c241998-12-22 05:19:29 +0000124 rep = ""
125 for host in self.hosts.keys():
126 attrs = self.hosts[host]
James Sextonb24cd052017-09-30 02:10:31 -0500127 rep += f"machine {host}\n\tlogin {attrs[0]}\n"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000128 if attrs[1]:
James Sextonb24cd052017-09-30 02:10:31 -0500129 rep += f"\taccount {attrs[1]}\n"
130 rep += f"\tpassword {attrs[2]}\n"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000131 for macro in self.macros.keys():
James Sextonb24cd052017-09-30 02:10:31 -0500132 rep += f"macdef {macro}\n"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000133 for line in self.macros[macro]:
James Sextonb24cd052017-09-30 02:10:31 -0500134 rep += line
135 rep += "\n"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000136 return rep
137
Tim Peters2344fae2001-01-15 00:50:52 +0000138if __name__ == '__main__':
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000139 print(netrc())