Added Fred Drake's netrc parser class.

This commit is contained in:
Guido van Rossum 1997-03-14 04:16:54 +00:00
parent 18aef3c102
commit 56d1e3a517
1 changed files with 100 additions and 0 deletions

View File

@ -542,6 +542,106 @@ def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
source.voidresp()
target.voidresp()
NoFileSpecified = "netrc.NoFileSpecified"
class Netrc:
__defuser = None
__defpasswd = None
__defacct = None
def __init__(self, filename=None):
if not filename:
if os.environ.has_key("HOME"):
filename = os.path.join(os.environ["HOME"], ".netrc")
else:
raise NoFileSpecified, "specify file to load or set $HOME"
self.__hosts = {}
self.__macros = {}
fp = open(filename, "r")
in_macro = 0
while 1:
line = fp.readline()
if not line: break
if in_macro and string.strip(line):
macro_lines.append(line)
continue
elif in_macro:
self.__macros[macro_name] = tuple(macro_lines)
in_macro = 0
words = string.split(line)
host = user = passwd = acct = None
default = 0
i = 0
while i < len(words):
w1 = words[i]
if i+1 < len(words):
w2 = words[i + 1]
else:
w2 = None
if w1 == 'default':
default = 1
elif w1 == 'machine' and w2:
host = string.lower(w2)
i = i + 1
elif w1 == 'login' and w2:
user = w2
i = i + 1
elif w1 == 'password' and w2:
passwd = w2
i = i + 1
elif w1 == 'account' and w2:
acct = w2
i = i + 1
elif w1 == 'macdef' and w2:
macro_name = w2
macro_lines = []
in_macro = 1
break
i = i + 1
if default:
self.__defuser = user or self.__defuser
self.__defpasswd = passwd or self.__defpasswd
self.__defacct = acct or self.__defacct
if host:
if self.__hosts.has_key(host):
ouser, opasswd, oacct = self.__hosts[host]
user = user or ouser
passwd = passwd or opasswd
acct = acct or oacct
self.__hosts[host] = user, passwd, acct
fp.close()
def get_hosts(self):
"""Return a list of hosts mentioned in the .netrc file."""
return self.__hosts.keys()
def get_account(self, host):
"""Returns login information for the named host.
The return value is a triple containing userid, password, and the
accounting field.
"""
host = string.lower(host)
user, passwd, acct = None, None, None
if self.__hosts.has_key(host):
user, passwd, acct = self.__hosts[host]
user = user or self.__defuser
passwd = passwd or self.__defpasswd
acct = acct or self.__defacct
return user, passwd, acct
def get_macros(self):
"""Return a list of all defined macro names."""
return self.__macros.keys()
def get_macro(self, macro):
"""Return a sequence of lines which define a named macro."""
return self.__macros[macro]
def test():
'''Test program.
Usage: ftp [-d] host [-l[dir]] [-d[dir]] [-p] [file] ...'''