ftplib --- FTP 協(xié)議客戶端?
源代碼: Lib/ftplib.py
本模塊定義了 FTP 類和一些相關(guān)項(xiàng)目。FTP 類實(shí)現(xiàn)了 FTP 協(xié)議的客戶端。可以用該類編寫 Python 程序,執(zhí)行各種自動(dòng)化的 FTP 任務(wù),如鏡像其他 FTP 服務(wù)器。urllib.request 模塊也用它來(lái)處理使用了 FTP 的 URL。關(guān)于 FTP(文件傳輸協(xié)議)的詳情請(qǐng)參閱 Internet RFC 959。
以下是使用 ftplib 模塊的會(huì)話示例:
>>> 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()
這個(gè)模塊定義了以下內(nèi)容:
-
class
ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None)? Return a new instance of the
FTPclass. When host is given, the method callconnect(host)is made. When user is given, additionally the method calllogin(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.>>> 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語(yǔ)句。在 3.3 版更改: 添加了 source_address 參數(shù)。
-
class
ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None)? 一個(gè)
FTP的子類,它為 FTP 添加了 TLS 支持,如 RFC 4217 所述。它將像通常一樣連接到 21 端口,暗中保護(hù)在身份驗(yàn)證前的 FTP 控制連接。而保護(hù)數(shù)據(jù)連接需要用戶明確調(diào)用prot_p()方法。context 是一個(gè)ssl.SSLContext對(duì)象,該對(duì)象可以將 SSL 配置選項(xiàng)、證書和私鑰打包放入一個(gè)單獨(dú)的(可以長(zhǎng)久存在的)結(jié)構(gòu)中。請(qǐng)閱讀 安全考量 以獲取最佳實(shí)踐。keyfile 和 certfile 是可以代替 context 的傳統(tǒng)方案,它們可以分別指向 PEM 格式的私鑰和證書鏈文件,用于進(jìn)行 SSL 連接。
3.2 新版功能.
在 3.3 版更改: 添加了 source_address 參數(shù)。
在 3.4 版更改: 本類現(xiàn)在支持通過(guò)
ssl.SSLContext.check_hostname和 服務(wù)器名稱提示 (參閱ssl.HAS_SNI)進(jìn)行主機(jī)名檢查。3.6 版后已移除: keyfile 和 certfile 已棄用并轉(zhuǎn)而推薦 context。 請(qǐng)改用
ssl.SSLContext.load_cert_chain()或讓ssl.create_default_context()為你選擇系統(tǒng)所信任的 CA 證書。以下是使用
FTP_TLS類的會(huì)話示例:>>> 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? 從服務(wù)器收到意外答復(fù)時(shí),將引發(fā)本異常。
-
exception
ftplib.error_temp? 收到表示臨時(shí)錯(cuò)誤的錯(cuò)誤代碼(響應(yīng)代碼在 400--499 范圍內(nèi))時(shí),將引發(fā)本異常。
-
exception
ftplib.error_perm? 收到表示永久性錯(cuò)誤的錯(cuò)誤代碼(響應(yīng)代碼在 500--599 范圍內(nèi))時(shí),將引發(fā)本異常。
-
exception
ftplib.error_proto? 從服務(wù)器收到不符合 FTP 響應(yīng)規(guī)范的答復(fù),比如以數(shù)字 1--5 開頭時(shí),將引發(fā)本異常。
-
ftplib.all_errors? The set of all exceptions (as a tuple) that methods of
FTPinstances 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 asOSError.
參見
netrc模塊.netrc文件格式解析器。FTP 客戶端在響應(yīng)用戶之前,通常使用.netrc文件來(lái)加載用戶認(rèn)證信息。
FTP 對(duì)象?
一些方法可以按照兩種方式來(lái)使用:一種處理文本文件,另一種處理二進(jìn)制文件。方法名稱與相應(yīng)的命令相同,文本版中命令后面跟著 lines,二進(jìn)制版中命令后面跟著 binary。
FTP 實(shí)例具有下列方法:
-
FTP.set_debuglevel(level)? 設(shè)置實(shí)例的調(diào)試級(jí)別,它控制著調(diào)試信息的數(shù)量。默認(rèn)值
0不產(chǎn)生調(diào)試信息。值1產(chǎn)生中等數(shù)量的調(diào)試信息,通常每個(gè)請(qǐng)求產(chǎn)生一行。大于或等于2的值產(chǎn)生的調(diào)試信息最多,F(xiàn)TP 控制連接上發(fā)送和接收的每一行都將被記錄下來(lái)。
-
FTP.connect(host='', port=0, timeout=None, source_address=None)? 連接到給定的主機(jī)和端口。默認(rèn)端口號(hào)由 FTP 協(xié)議規(guī)范規(guī)定,為
21。偶爾才需要指定其他端口號(hào)。每個(gè)實(shí)例只應(yīng)調(diào)用一次本函數(shù),如果在創(chuàng)建實(shí)例時(shí)就傳入了 host,則根本不應(yīng)調(diào)用它。所有其他方法只能在建立連接后使用??蛇x參數(shù) timeout 指定連接嘗試的超時(shí)(以秒為單位)。如果沒(méi)有傳入 timeout,將使用全局默認(rèn)超時(shí)設(shè)置。source_address 是一個(gè) 2 元組(host, port),套接字在連接前綁定它,作為其源地址。在 3.3 版更改: 添加了 source_address 參數(shù)。
-
FTP.getwelcome()? 返回服務(wù)器發(fā)送的歡迎消息,作為連接開始的回復(fù)。(該消息有時(shí)包含與用戶有關(guān)的免責(zé)聲明或幫助信息。)
-
FTP.login(user='anonymous', passwd='', acct='')? 以 user 的身份登錄。passwd 和 acct 是可選參數(shù),默認(rèn)為空字符串。如果沒(méi)有指定 user,則默認(rèn)為
'anonymous'。如果 user 為'anonymous',那么默認(rèn)的 passwd 是'anonymous@'。連接建立后,每個(gè)實(shí)例只應(yīng)調(diào)用一次本函數(shù);如果在創(chuàng)建實(shí)例時(shí)傳入了 host 和 user,則完全不應(yīng)該調(diào)用本函數(shù)。在客戶端登錄后,才允許執(zhí)行大多數(shù) FTP 命令。acct 參數(shù)提供記賬信息 ("accounting information");僅少數(shù)系統(tǒng)實(shí)現(xiàn)了該特性。
-
FTP.abort()? 中止正在進(jìn)行的文件傳輸。本方法并不總是有效,但值得一試。
-
FTP.sendcmd(cmd)? 將一條簡(jiǎn)單的命令字符串發(fā)送到服務(wù)器,返回響應(yīng)的字符串。
-
FTP.voidcmd(cmd)? 將一條簡(jiǎn)單的命令字符串發(fā)送到服務(wù)器,并處理響應(yīng)內(nèi)容。如果收到的響應(yīng)代碼表示的是成功(代碼范圍 200--299),則不返回任何內(nèi)容。否則將引發(fā)
error_reply。
-
FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)? 以二進(jìn)制傳輸模式下載文件。cmd 應(yīng)為恰當(dāng)?shù)?
RETR命令:'RETR 文件名'。callback 函數(shù)會(huì)在收到每個(gè)數(shù)據(jù)塊時(shí)調(diào)用,傳入的參數(shù)是表示數(shù)據(jù)塊的一個(gè)字節(jié)。為執(zhí)行實(shí)際傳輸,創(chuàng)建了底層套接字對(duì)象,可選參數(shù) blocksize 指定了讀取該對(duì)象時(shí)的最大塊大?。ㄟ@也是傳入 callback 的數(shù)據(jù)塊的最大大小)。已經(jīng)選擇了合理的默認(rèn)值。rest 的含義與transfercmd()方法中的含義相同。
-
FTP.retrlines(cmd, callback=None)? Retrieve a file or directory listing in ASCII transfer mode. cmd should be an appropriate
RETRcommand (seeretrbinary()) or a command such asLISTorNLST(usually just the string'LIST').LISTretrieves a list of files and information about those files.NLSTretrieves 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 tosys.stdout.
-
FTP.set_pasv(val)? 如果 val 為 true,則打開“被動(dòng)”模式,否則禁用被動(dòng)模式。默認(rèn)下被動(dòng)模式是打開的。
-
FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)? 以二進(jìn)制傳輸模式存儲(chǔ)文件。 cmd 應(yīng)為恰當(dāng)?shù)?
STOR命令:"STOR filename"。fp 是一個(gè) 文件對(duì)象 (以二進(jìn)制模式打開),將使用它的read()方法讀取它,用于提供要存儲(chǔ)的數(shù)據(jù),直到遇到 EOF,讀取時(shí)的塊大小為 blocksize。 參數(shù) blocksize 的默認(rèn)值為 8192。 可選參數(shù) callback 是單參數(shù)函數(shù),在每個(gè)數(shù)據(jù)塊發(fā)送后都會(huì)用該數(shù)據(jù)塊調(diào)用它。rest 的含義與transfercmd()方法中的含義相同。在 3.2 版更改: 添加了 rest 參數(shù)。
-
FTP.storlines(cmd, fp, callback=None)? Store a file in ASCII transfer mode. cmd should be an appropriate
STORcommand (seestorbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using itsreadline()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 數(shù)據(jù)連接上開始傳輸數(shù)據(jù)。如果傳輸處于活動(dòng)狀態(tài),傳輸命令由 cmd 指定,需發(fā)送
EPRT或PORT命令,然后接受連接 (accept)。如果服務(wù)器是被動(dòng)服務(wù)器,需發(fā)送EPSV或PASV命令,連接到服務(wù)器 (connect),然后啟動(dòng)傳輸命令。兩種方式都將返回用于連接的套接字。If optional rest is given, a
RESTcommand 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. Thetransfercmd()method, therefore, converts rest to a string, but no check is performed on the string's contents. If the server does not recognize theRESTcommand, anerror_replyexception will be raised. If this happens, simply calltransfercmd()without a rest argument.
-
FTP.ntransfercmd(cmd, rest=None)? 類似于
transfercmd(),但返回一個(gè)元組,包括數(shù)據(jù)連接和數(shù)據(jù)的預(yù)計(jì)大小。如果預(yù)計(jì)大小無(wú)法計(jì)算,則返回的預(yù)計(jì)大小為None。cmd 和 rest 的含義與transfercmd()中的相同。
-
FTP.mlsd(path="", facts=[])? 使用
MLSD命令以標(biāo)準(zhǔn)格式列出目錄內(nèi)容 (RFC 3659)。如果省略 path 則使用當(dāng)前目錄。facts 是字符串列表,表示所需的信息類型(如["type", "size", "perm"])。返回一個(gè)生成器對(duì)象,每個(gè)在 path 中找到的文件都將在該對(duì)象中生成兩個(gè)元素的元組。第一個(gè)元素是文件名,第二個(gè)元素是該文件的 facts 的字典。該字典的內(nèi)容受 facts 參數(shù)限制,但不能保證服務(wù)器會(huì)返回所有請(qǐng)求的 facts。3.3 新版功能.
-
FTP.nlst(argument[, ...])? 返回一個(gè)文件名列表,文件名由?
NLST命令返回。可選參數(shù) argument 是待列出的目錄(默認(rèn)為當(dāng)前服務(wù)器目錄)??梢允褂枚鄠€(gè)參數(shù),將非標(biāo)準(zhǔn)選項(xiàng)傳遞給NLST命令。注解
如果目標(biāo)服務(wù)器支持相關(guān)命令,那么
mlsd()提供的 API 更好。
-
FTP.dir(argument[, ...])? 生成目錄列表,即
LIST命令所返回的結(jié)果,并將其打印到標(biāo)準(zhǔn)輸出??蛇x參數(shù) argument 是待列出的目錄(默認(rèn)為當(dāng)前服務(wù)器目錄)??梢允褂枚鄠€(gè)參數(shù),將非標(biāo)準(zhǔn)選項(xiàng)傳遞給LIST命令。如果最后一個(gè)參數(shù)是一個(gè)函數(shù),它將被用作 callback 函數(shù),與retrlines()中的相同,默認(rèn)將打印到sys.stdout。本方法返回None。注解
如果目標(biāo)服務(wù)器支持相關(guān)命令,那么
mlsd()提供的 API 更好。
-
FTP.rename(fromname, toname)? 將服務(wù)器上的文件 fromname 重命名為 toname。
-
FTP.delete(filename)? 將服務(wù)器上名為 filename 的文件刪除。如果刪除成功,返回響應(yīng)文本,如果刪除失敗,在權(quán)限錯(cuò)誤時(shí)引發(fā)
error_perm,在其他錯(cuò)誤時(shí)引發(fā)error_reply。
-
FTP.cwd(pathname)? 設(shè)置服務(wù)器端的當(dāng)前目錄。
-
FTP.mkd(pathname)? 在服務(wù)器上創(chuàng)建一個(gè)新目錄。
-
FTP.pwd()? 返回服務(wù)器上當(dāng)前目錄的路徑。
-
FTP.rmd(dirname)? 將服務(wù)器上名為 dirname 的目錄刪除。
-
FTP.size(filename)? 請(qǐng)求服務(wù)器上名為 filename 的文件大小。成功后以整數(shù)返回文件大小,未成功則返回
None。注意,SIZE不是標(biāo)準(zhǔn)命令,但通常許多服務(wù)器的實(shí)現(xiàn)都支持該命令。
FTP_TLS 對(duì)象?
FTP_TLS 類繼承自 FTP,它定義了下述其他對(duì)象:
-
FTP_TLS.ssl_version? 欲采用的 SSL 版本(默認(rèn)為
ssl.PROTOCOL_SSLv23)。
-
FTP_TLS.auth()? 通過(guò)使用 TLS 或 SSL 來(lái)設(shè)置一個(gè)安全控制連接,具體取決于
ssl_version屬性是如何設(shè)置的。在 3.4 版更改: 此方法現(xiàn)在支持使用
ssl.SSLContext.check_hostname和 服務(wù)器名稱指示 (參見ssl.HAS_SNI) 進(jìn)行主機(jī)名檢查。
-
FTP_TLS.ccc()? 將控制通道回復(fù)為純文本。 這適用于發(fā)揮知道如何使用非安全 FTP 處理 NAT 而無(wú)需打開固定端口的防火墻的優(yōu)勢(shì)。
3.3 新版功能.
-
FTP_TLS.prot_p()? 設(shè)置加密數(shù)據(jù)連接。
-
FTP_TLS.prot_c()? 設(shè)置明文數(shù)據(jù)連接。
