netrc --- netrc 文件处理

源代码: Lib/netrc.py


netrc 类解析并封装了 Unix 的 ftp 程序和其他 FTP 客户端所使用的 netrc 文件格式。

class netrc.netrc([file])

netrc 的实例或其子类的实例会被用来封装来自 netrc 文件的数据。 如果有初始化参数,它将指明要解析的文件。 如果未给出参数,则位于用户家目录的 .netrc 文件 -- 即 os.path.expanduser() 所确定的文件 -- 将会被读取。 在其他情况下,则将引发 FileNotFoundError 异常。 解析错误将引发 NetrcParseError 并附带诊断信息,包括文件名、行号以及终止令牌。 如果在 POSIX 系统上未指明参数,则当 .netrc 文件中有密码时,如果文件归属或权限不安全(归属的用户不是运行进程的用户,或者可供任何其他用户读取或写入)将引发 NetrcParseError。 这实现了与 ftp 和其他使用 .netrc 的程序同等的安全行为。

3.4 版更變: 添加了 POSIX 权限检查。

3.7 版更變: os.path.expanduser() is used to find the location of the .netrc file when file is not passed as argument.

exception netrc.NetrcParseError

Exception raised by the netrc class when syntactical errors are encountered in source text. Instances of this exception provide three interesting attributes: msg is a textual explanation of the error, filename is the name of the source file, and lineno gives the line number on which the error was found.

netrc Objects

A netrc instance has the following methods:

netrc.authenticators(host)

Return a 3-tuple (login, account, password) of authenticators for host. If the netrc file did not contain an entry for the given host, return the tuple associated with the 'default' entry. If neither matching host nor default entry is available, return None.

netrc.__repr__()

Dump the class data as a string in the format of a netrc file. (This discards comments and may reorder the entries.)

Instances of netrc have public instance variables:

netrc.hosts

Dictionary mapping host names to (login, account, password) tuples. The 'default' entry, if any, is represented as a pseudo-host by that name.

netrc.macros

Dictionary mapping macro names to string lists.

備註

Passwords are limited to a subset of the ASCII character set. All ASCII punctuation is allowed in passwords, however, note that whitespace and non-printable characters are not allowed in passwords. This is a limitation of the way the .netrc file is parsed and may be removed in the future.