netrc --- netrc 檔案處理

原始碼:Lib/netrc.py


netrc 類別能夠剖析 (parse) 並封裝 (encapsulate) netrc 檔案格式,以供 Unix ftp 程式和其他 FTP 用戶端使用。

class netrc.netrc([file])

netrc 實例或其子類別實例能夠封裝來自 netrc 檔案的資料。可用初始化引數(如有給定)指定要剖析的檔案,如果未給定引數,則將讀取(由 os.path.expanduser() 指定的)使用者主目錄中的 .netrc 檔案,否則將引發 FileNotFoundError 例外。剖析錯誤會引發 NetrcParseError,其帶有包括檔案名稱、列號和終止 token 的診斷資訊。如果在 POSIX 系統上未指定引數,且若檔案所有權或權限不安全(擁有者與運行該行程的使用者不同,或者可供任何其他使用者讀取或寫入),存有密碼的 .netrc 檔案將會引發 NetrcParseError。這實作了與 ftp 和其他使用 .netrc 程式等效的安全行為。

在 3.4 版的變更: 新增了 POSIX 權限檢查。

在 3.7 版的變更: 當未傳遞 file 引數時,os.path.expanduser() 可用於查找 .netrc 檔案的位置。

在 3.10 版的變更: netrc 在使用特定語言環境編碼前會先嘗試 UTF-8 編碼。netrc 檔案中的條目就不再需要包含所有 token,缺少的 token 值被預設為空字串。現在所有 token 及其值都可以包含任意字元,例如空格和非 ASCII 字元。如果登入名稱為匿名,就不會觸發安全檢查。

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

Textual explanation of the error.

filename

The name of the source file.

lineno

The line number on which the error was found.

netrc 物件

netrc 實例具有以下方法:

netrc.authenticators(host)

回傳 host 身份驗證器的三元素 tuple (login, account, password)。如果 netrc 檔案不包含給定主機的條目,則回傳與 'default' 條目關聯的 tuple。如果並無匹配主機且預設條目也不可用則回傳 None

netrc.__repr__()

將類別資料傾印 (dump) 為 netrc 檔案格式的字串。(這會將註解移除,並可能會對條目重新排序。)

netrc 的實例具有公開實例變數:

netrc.hosts

將主機名稱對映到 (login, account, password) tuple 的字典。'default' 條目(如存在)表示為該名稱對應到的偽主機 (pseudo-host)。

netrc.macros

巨集 (macro) 名稱與字串 list(串列)的對映字典。