• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""An object-oriented interface to .netrc files."""
2
3# Module and documentation by Eric S. Raymond, 21 Dec 1998
4
5import os, shlex, stat
6
7__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):
13        self.filename = filename
14        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
21
22class netrc:
23    def __init__(self, file=None):
24        default_netrc = file is None
25        if file is None:
26            try:
27                file = os.path.join(os.environ['HOME'], ".netrc")
28            except KeyError:
29                raise OSError("Could not find .netrc: $HOME is not set")
30        self.hosts = {}
31        self.macros = {}
32        with open(file) as fp:
33            self._parse(file, fp, default_netrc)
34
35    def _parse(self, file, fp, default_netrc):
36        lexer = shlex.shlex(fp)
37        lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
38        lexer.commenters = lexer.commenters.replace('#', '')
39        while 1:
40            # Look for a machine, default, or macdef top-level keyword
41            saved_lineno = lexer.lineno
42            toplevel = tt = lexer.get_token()
43            if not tt:
44                break
45            elif tt[0] == '#':
46                if lexer.lineno == saved_lineno and len(tt) == 1:
47                    lexer.instream.readline()
48                continue
49            elif tt == 'machine':
50                entryname = lexer.get_token()
51            elif tt == 'default':
52                entryname = 'default'
53            elif tt == 'macdef':                # Just skip to end of macdefs
54                entryname = lexer.get_token()
55                self.macros[entryname] = []
56                lexer.whitespace = ' \t'
57                while 1:
58                    line = lexer.instream.readline()
59                    if not line or line == '\012':
60                        lexer.whitespace = ' \t\r\n'
61                        break
62                    self.macros[entryname].append(line)
63                continue
64            else:
65                raise NetrcParseError(
66                    "bad toplevel token %r" % tt, file, lexer.lineno)
67
68            # We're looking at start of an entry for a named machine or default.
69            login = ''
70            account = password = None
71            self.hosts[entryname] = {}
72            while 1:
73                tt = lexer.get_token()
74                if (tt.startswith('#') or
75                    tt in {'', 'machine', 'default', 'macdef'}):
76                    if password:
77                        self.hosts[entryname] = (login, account, password)
78                        lexer.push_token(tt)
79                        break
80                    else:
81                        raise NetrcParseError(
82                            "malformed %s entry %s terminated by %s"
83                            % (toplevel, entryname, repr(tt)),
84                            file, lexer.lineno)
85                elif tt == 'login' or tt == 'user':
86                    login = lexer.get_token()
87                elif tt == 'account':
88                    account = lexer.get_token()
89                elif tt == 'password':
90                    if os.name == 'posix' and default_netrc:
91                        prop = os.fstat(fp.fileno())
92                        if prop.st_uid != os.getuid():
93                            import pwd
94                            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)
111                    password = lexer.get_token()
112                else:
113                    raise NetrcParseError("bad follower token %r" % tt,
114                                          file, lexer.lineno)
115
116    def authenticators(self, host):
117        """Return a (user, account, password) tuple for given host."""
118        if host in self.hosts:
119            return self.hosts[host]
120        elif 'default' in self.hosts:
121            return self.hosts['default']
122        else:
123            return None
124
125    def __repr__(self):
126        """Dump the class data in the format of a .netrc file."""
127        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
141if __name__ == '__main__':
142    print(netrc())
143