14.3. netrc — netrc 文件处理

源代码: Lib/netrc.py


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

class netrc.netrc([file])

A netrc instance or subclass instance encapsulates data from a netrc file. The initialization argument, if present, specifies the file to parse. If no argument is given, the file .netrc in the user’s home directory will be read. Parse errors will raise NetrcParseError with diagnostic information including the file name, line number, and terminating token. If no argument is specified on a POSIX system, the presence of passwords in the .netrc file will raise a NetrcParseError if the file ownership or permissions are insecure (owned by a user other than the user running the process, or accessible for read or write by any other user). This implements security behavior equivalent to that of ftp and other programs that use .netrc.

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

exception netrc.NetrcParseError

当在源文本中遇到语法错误时由 netrc 类引发的异常。 此异常的实例提供了三个有用属性: msg 为错误的文本说明,filename 为源文件的名称,而 lineno 给出了错误所在的行号。

14.3.1. netrc 对象

netrc 实例具有下列方法:

netrc.authenticators(host)

针对 host 的身份验证者返回一个 3 元组 (login, account, password)。 如果 netrc 文件不包含针对给定主机的条目,则返回关联到 ‘default’ 条目的元组。 如果匹配的主机或默认条目均不可用,则返回 None

netrc.__repr__()

将类数据以 netrc 文件的格式转储为一个字符串。 (这会丢弃注释并可能重排条目顺序。)

netrc 的实例具有一些公共实例变量:

netrc.hosts

将主机名映射到 (login, account, password) 元组的字典。 如果存在 ‘default’ 条目,则会表示为使用该名称的伪主机。

netrc.macros

将宏名称映射到字符串列表的字典。

注解

密码会被限制为 ASCII 字符集的一个子集。 所有 ASCII 标点符号均可用作密码,但是要注意空白符和非打印字符不允许用作密码。 这是 .netrc 文件解析方式带来的限制,在未来可能会被解除。