ftplib --- FTP 協議客戶端?

源代碼: Lib/ftplib.py


本模塊定義了 FTP 類和一些相關項目。FTP 類實現了 FTP 協議的客戶端??梢杂迷擃惥帉?Python 程序,執行各種自動化的 FTP 任務,如鏡像其他 FTP 服務器。urllib.request 模塊也用它來處理使用了 FTP 的 URL。關于 FTP(文件傳輸協議)的詳情請參閱 Internet RFC 959。

以下是使用 ftplib 模塊的會話示例:

>>> from ftplib import FTP
>>> ftp = FTP('ftp.debian.org')     # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd anonymous@
'230 Login successful.'
>>> ftp.cwd('debian')               # change into "debian" directory
>>> ftp.retrlines('LIST')           # list directory contents
-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
...
drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>>     ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()

這個模塊定義了以下內容:

class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None)?

Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting.

FTP 類支持 with 語句,例如:

>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
...     ftp.login()
...     ftp.dir()
... 
'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
>>>

在 3.2 版更改: 支持了 with 語句。

在 3.3 版更改: 添加了 source_address 參數。

class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None)?

一個 FTP 的子類,它為 FTP 添加了 TLS 支持,如 RFC 4217 所述。它將像通常一樣連接到 21 端口,暗中保護在身份驗證前的 FTP 控制連接。而保護數據連接需要用戶明確調用 prot_p() 方法。context 是一個 ssl.SSLContext 對象,該對象可以將 SSL 配置選項、證書和私鑰打包放入一個單獨的(可以長久存在的)結構中。請閱讀 安全考量 以獲取最佳實踐。

keyfilecertfile 是可以代替 context 的傳統方案,它們可以分別指向 PEM 格式的私鑰和證書鏈文件,用于進行 SSL 連接。

3.2 新版功能.

在 3.3 版更改: 添加了 source_address 參數。

在 3.4 版更改: 本類現在支持通過 ssl.SSLContext.check_hostname服務器名稱提示 (參閱 ssl.HAS_SNI)進行主機名檢查。

3.6 版后已移除: keyfilecertfile 已棄用并轉而推薦 context。 請改用 ssl.SSLContext.load_cert_chain() 或讓 ssl.create_default_context() 為你選擇系統所信任的 CA 證書。

以下是使用 FTP_TLS 類的會話示例:

>>> ftps = FTP_TLS('ftp.pureftpd.org')
>>> ftps.login()
'230 Anonymous user logged in'
>>> ftps.prot_p()
'200 Data protection level set to "private"'
>>> ftps.nlst()
['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']
exception ftplib.error_reply?

從服務器收到意外答復時,將引發本異常。

exception ftplib.error_temp?

收到表示臨時錯誤的錯誤代碼(響應代碼在 400--499 范圍內)時,將引發本異常。

exception ftplib.error_perm?

收到表示永久性錯誤的錯誤代碼(響應代碼在 500--599 范圍內)時,將引發本異常。

exception ftplib.error_proto?

從服務器收到不符合 FTP 響應規范的答復,比如以數字 1--5 開頭時,將引發本異常。

ftplib.all_errors?

The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as OSError.

參見

netrc 模塊

.netrc 文件格式解析器。FTP 客戶端在響應用戶之前,通常使用 .netrc 文件來加載用戶認證信息。

FTP 對象?

一些方法可以按照兩種方式來使用:一種處理文本文件,另一種處理二進制文件。方法名稱與相應的命令相同,文本版中命令后面跟著 lines,二進制版中命令后面跟著 binary

FTP 實例具有下列方法:

FTP.set_debuglevel(level)?

設置實例的調試級別,它控制著調試信息的數量。默認值 0 不產生調試信息。值 1 產生中等數量的調試信息,通常每個請求產生一行。大于或等于 2 的值產生的調試信息最多,FTP 控制連接上發送和接收的每一行都將被記錄下來。

FTP.connect(host='', port=0, timeout=None, source_address=None)?

連接到給定的主機和端口。默認端口號由 FTP 協議規范規定,為 21。偶爾才需要指定其他端口號。每個實例只應調用一次本函數,如果在創建實例時就傳入了 host,則根本不應調用它。所有其他方法只能在建立連接后使用。可選參數 timeout 指定連接嘗試的超時(以秒為單位)。如果沒有傳入 timeout,將使用全局默認超時設置。source_address 是一個 2 元組 (host, port),套接字在連接前綁定它,作為其源地址。

在 3.3 版更改: 添加了 source_address 參數。

FTP.getwelcome()?

返回服務器發送的歡迎消息,作為連接開始的回復。(該消息有時包含與用戶有關的免責聲明或幫助信息。)

FTP.login(user='anonymous', passwd='', acct='')?

user 的身份登錄。passwdacct 是可選參數,默認為空字符串。如果沒有指定 user,則默認為 'anonymous'。如果 user'anonymous',那么默認的 passwd'anonymous@'。連接建立后,每個實例只應調用一次本函數;如果在創建實例時傳入了 host 和 user,則完全不應該調用本函數。在客戶端登錄后,才允許執行大多數 FTP 命令。acct 參數提供記賬信息 ("accounting information");僅少數系統實現了該特性。

FTP.abort()?

中止正在進行的文件傳輸。本方法并不總是有效,但值得一試。

FTP.sendcmd(cmd)?

將一條簡單的命令字符串發送到服務器,返回響應的字符串。

FTP.voidcmd(cmd)?

將一條簡單的命令字符串發送到服務器,并處理響應內容。如果收到的響應代碼表示的是成功(代碼范圍 200--299),則不返回任何內容。否則將引發 error_reply。

FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)?

以二進制傳輸模式下載文件。cmd 應為恰當的 RETR 命令:'RETR 文件名'。callback 函數會在收到每個數據塊時調用,傳入的參數是表示數據塊的一個字節。為執行實際傳輸,創建了底層套接字對象,可選參數 blocksize 指定了讀取該對象時的最大塊大?。ㄟ@也是傳入 callback 的數據塊的最大大?。?。已經選擇了合理的默認值。rest 的含義與 transfercmd() 方法中的含義相同。

FTP.retrlines(cmd, callback=None)?

Retrieve a file or directory listing in ASCII transfer mode. cmd should be an appropriate RETR command (see retrbinary()) or a command such as LIST or NLST (usually just the string 'LIST'). LIST retrieves a list of files and information about those files. NLST retrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout.

FTP.set_pasv(val)?

如果 val 為 true,則打開“被動”模式,否則禁用被動模式。默認下被動模式是打開的。

FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)?

以二進制傳輸模式存儲文件。 cmd 應為恰當的 STOR 命令: "STOR filename"。fp 是一個 文件對象 (以二進制模式打開),將使用它的 read() 方法讀取它,用于提供要存儲的數據,直到遇到 EOF,讀取時的塊大小為 blocksize。 參數 blocksize 的默認值為 8192。 可選參數 callback 是單參數函數,在每個數據塊發送后都會用該數據塊調用它。rest 的含義與 transfercmd() 方法中的含義相同。

在 3.2 版更改: 添加了 rest 參數。

FTP.storlines(cmd, fp, callback=None)?

Store a file in ASCII transfer mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.

FTP.transfercmd(cmd, rest=None)?

在 FTP 數據連接上開始傳輸數據。如果傳輸處于活動狀態,傳輸命令由 cmd 指定,需發送 EPRTPORT 命令,然后接受連接 (accept)。如果服務器是被動服務器,需發送 EPSVPASV 命令,連接到服務器 (connect),然后啟動傳輸命令。兩種方式都將返回用于連接的套接字。

If optional rest is given, a REST command is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file's bytes at the requested offset, skipping over the initial bytes. Note however that RFC 959 requires only that rest be a string containing characters in the printable range from ASCII code 33 to ASCII code 126. The transfercmd() method, therefore, converts rest to a string, but no check is performed on the string's contents. If the server does not recognize the REST command, an error_reply exception will be raised. If this happens, simply call transfercmd() without a rest argument.

FTP.ntransfercmd(cmd, rest=None)?

類似于 transfercmd(),但返回一個元組,包括數據連接和數據的預計大小。如果預計大小無法計算,則返回的預計大小為 None。cmdrest 的含義與 transfercmd() 中的相同。

FTP.mlsd(path="", facts=[])?

使用 MLSD 命令以標準格式列出目錄內容 (RFC 3659)。如果省略 path 則使用當前目錄。facts 是字符串列表,表示所需的信息類型(如 ["type", "size", "perm"])。返回一個生成器對象,每個在 path 中找到的文件都將在該對象中生成兩個元素的元組。第一個元素是文件名,第二個元素是該文件的 facts 的字典。該字典的內容受 facts 參數限制,但不能保證服務器會返回所有請求的 facts。

3.3 新版功能.

FTP.nlst(argument[, ...])?

返回一個文件名列表,文件名由?NLST 命令返回??蛇x參數 argument 是待列出的目錄(默認為當前服務器目錄)??梢允褂枚鄠€參數,將非標準選項傳遞給 NLST 命令。

注解

如果目標服務器支持相關命令,那么 mlsd() 提供的 API 更好。

FTP.dir(argument[, ...])?

生成目錄列表,即 LIST 命令所返回的結果,并將其打印到標準輸出。可選參數 argument 是待列出的目錄(默認為當前服務器目錄)??梢允褂枚鄠€參數,將非標準選項傳遞給 LIST 命令。如果最后一個參數是一個函數,它將被用作 callback 函數,與 retrlines() 中的相同,默認將打印到 sys.stdout。本方法返回 None。

注解

如果目標服務器支持相關命令,那么 mlsd() 提供的 API 更好。

FTP.rename(fromname, toname)?

將服務器上的文件 fromname 重命名為 toname

FTP.delete(filename)?

將服務器上名為 filename 的文件刪除。如果刪除成功,返回響應文本,如果刪除失敗,在權限錯誤時引發 error_perm,在其他錯誤時引發 error_reply。

FTP.cwd(pathname)?

設置服務器端的當前目錄。

FTP.mkd(pathname)?

在服務器上創建一個新目錄。

FTP.pwd()?

返回服務器上當前目錄的路徑。

FTP.rmd(dirname)?

將服務器上名為 dirname 的目錄刪除。

FTP.size(filename)?

請求服務器上名為 filename 的文件大小。成功后以整數返回文件大小,未成功則返回 None。注意,SIZE 不是標準命令,但通常許多服務器的實現都支持該命令。

FTP.quit()?

向服務器發送 QUIT 命令并關閉連接。 這是關閉一個連接的“禮貌”方式,但是如果服務器對 QUIT 命令的響應帶有錯誤消息則這會引發一個異常。 這意味著對 close() 方法的調用,它將使得 FTP 實例對后繼調用無效(見下文)。

FTP.close()?

單方面關閉連接。 這不該被應用于已經關閉的連接,例如成功調用 quit() 之后的連接。 在此調用之后 FTP 實例不應被繼續使用(在調用 close()quit() 之后你不能通過再次發起調用 login() 方法重新打開連接)。

FTP_TLS 對象?

FTP_TLS 類繼承自 FTP,它定義了下述其他對象:

FTP_TLS.ssl_version?

欲采用的 SSL 版本(默認為 ssl.PROTOCOL_SSLv23)。

FTP_TLS.auth()?

通過使用 TLS 或 SSL 來設置一個安全控制連接,具體取決于 ssl_version 屬性是如何設置的。

在 3.4 版更改: 此方法現在支持使用 ssl.SSLContext.check_hostname服務器名稱指示 (參見 ssl.HAS_SNI) 進行主機名檢查。

FTP_TLS.ccc()?

將控制通道回復為純文本。 這適用于發揮知道如何使用非安全 FTP 處理 NAT 而無需打開固定端口的防火墻的優勢。

3.3 新版功能.

FTP_TLS.prot_p()?

設置加密數據連接。

FTP_TLS.prot_c()?

設置明文數據連接。