13.4. netrc — netrc 文件处理

1.5.2 新版功能.

源代码: 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.

在 2.7.6 版更改: Added the POSIX permissions check.

exception netrc.NetrcParseError

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

13.4.1. netrc 对象

netrc 实例具有下列方法:


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


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

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


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




Passwords are limited to a subset of the ASCII character set. Versions of this module prior to 2.3 were extremely limited. Starting with 2.3, 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.