ftplib
--- FTP 協定用戶端¶
原始碼:Lib/ftplib.py
這個模組定義了 FTP
類別和一些相關的項目。FTP
類別實作了 FTP 協定的用戶端。你可以使用它來編寫能夠執行各種 FTP 自動作業的 Python 程式,例如鏡像 (mirror) 其他 FTP 伺服器。urllib.request
模組也使用它來處理使用 FTP 的 URL。有關 FTP(檔案傳輸協定)的更多資訊,請參閱 RFC 959。
預設編碼是 UTF-8,遵循 RFC 2640。
Availability:非 Emscripten、非 WASI。
此模組在 WebAssembly 平台 wasm32-emscripten
和 wasm32-wasi
上不起作用或無法使用。有關更多資訊,請參閱 WebAssembly 平台。
這是一個使用 ftplib
模組的會話範例:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org') # connect to host, default port
>>> ftp.login() # user anonymous, passwd anonymous@
'230 Login successful.'
>>> ftp.cwd('debian') # change into "debian" directory
'250 Directory successfully changed.'
>>> 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()
'221 Goodbye.'
Reference¶
FTP objects¶
- class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')¶
Return a new instance of the
FTP
class.- 參數:
host (str) -- The hostname to connect to. If given,
connect(host)
is implicitly called by the constructor.user (str) -- The username to log in with (default:
'anonymous'
). If given,login(host, passwd, acct)
is implicitly called by the constructor.passwd (str) -- The password to use when logging in. If not given, and if passwd is the empty string or
"-"
, a password will be automatically generated.acct (str) -- Account information to be used for the
ACCT
FTP command. Few systems implement this. See RFC-959 for more details.timeout (float | None) -- A timeout in seconds for blocking operations like
connect()
(default: the global default timeout setting).source_address (tuple | None) -- A 2-tuple
(host, port)
for the socket to bind to as its source address before connecting.encoding (str) -- The encoding for directories and filenames (default:
'utf-8'
).
>>> 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 參數。
在 3.9 版的變更: 如果 timeout 參數設定為零,它將引發
ValueError
以防止建立非阻塞 socket。新增了 encoding 參數,預設值從 Latin-1 更改為 UTF-8 以遵循 RFC 2640。Several
FTP
methods are available in two flavors: one for handling text files and another for binary files. The methods are named for the command which is used followed bylines
for the text version orbinary
for the binary version.FTP
實例具有以下方法:- set_debuglevel(level)¶
Set the instance's debugging level as an
int
. This controls the amount of debugging output printed. The debug levels are:0
(default): No debug output.1
: Produce a moderate amount of debug output, generally a single line per request.2
or higher: Produce the maximum amount of debugging output, logging each line sent and received on the control connection.
- connect(host='', port=0, timeout=None, source_address=None)¶
Connect to the given host and port. This function should be called only once for each instance; it should not be called if a host argument was given when the
FTP
instance was created. All otherFTP
methods can only be called after a connection has successfully been made.- 參數:
host (str) -- The host to connect to.
port (int) -- The TCP port to connect to (default:
21
, as specified by the FTP protocol specification). It is rarely needed to specify a different port number.timeout (float | None) -- A timeout in seconds for the connection attempt (default: the global default timeout setting).
source_address (tuple | None) -- A 2-tuple
(host, port)
for the socket to bind to as its source address before connecting.
引發一個附帶引數
self
、host
、port
的稽核事件ftplib.connect
。在 3.3 版的變更: 新增 source_address 參數。
- getwelcome()¶
回傳伺服器為回應初始連線而發送的歡迎訊息。(此訊息有時會包含與使用者相關的免責聲明或幫助資訊。)
- login(user='anonymous', passwd='', acct='')¶
Log on to the connected FTP server. This function should be called only once for each instance, after a connection has been established; it should not be called if the host and user arguments were given when the
FTP
instance was created. Most FTP commands are only allowed after the client has logged in.- 參數:
user (str) -- The username to log in with (default:
'anonymous'
).passwd (str) -- The password to use when logging in. If not given, and if passwd is the empty string or
"-"
, a password will be automatically generated.acct (str) -- Account information to be used for the
ACCT
FTP command. Few systems implement this. See RFC-959 for more details.
- abort()¶
中止正在進行的檔案傳輸。使用它並不是都會成功,但值得一試。
- voidcmd(cmd)¶
Send a simple command string to the server and handle the response. Return the response string if the response code corresponds to success (codes in the range 200--299). Raise
error_reply
otherwise.引發一個附帶引數
self
、cmd
的稽核事件ftplib.sendcmd
。
- retrbinary(cmd, callback, blocksize=8192, rest=None)¶
Retrieve a file in binary transfer mode.
- 參數:
cmd (str) -- An appropriate
STOR
command:"STOR filename"
.callback (callable) -- A single parameter callable that is called for each block of data received, with its single argument being the data as
bytes
.blocksize (int) -- The maximum chunk size to read on the low-level
socket
object created to do the actual transfer. This also corresponds to the largest size of data that will be passed to callback. Defaults to8192
.rest (int) -- A
REST
command to be sent to the server. See the documentation for the rest parameter of thetransfercmd()
method.
- retrlines(cmd, callback=None)¶
Retrieve a file or directory listing in the encoding specified by the encoding parameter at initialization. cmd should be an appropriate
RETR
command (seeretrbinary()
) or a command such asLIST
orNLST
(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 tosys.stdout
.
- set_pasv(val)¶
如果 val 為真,則啟用「被動」模式,否則禁用被動模式。被動模式預設開啟。
- storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)¶
Store a file in binary transfer mode.
- 參數:
cmd (str) -- An appropriate
STOR
command:"STOR filename"
.fp (file object) -- A file object (opened in binary mode) which is read until EOF, using its
read()
method in blocks of size blocksize to provide the data to be stored.blocksize (int) -- The read block size. Defaults to
8192
.callback (callable) -- A single parameter callable that is called for each block of data sent, with its single argument being the data as
bytes
.rest (int) -- A
REST
command to be sent to the server. See the documentation for the rest parameter of thetransfercmd()
method.
在 3.2 版的變更: The rest parameter was added.
- storlines(cmd, fp, callback=None)¶
以行模式 (line mode) 儲存檔案。 cmd 應是一個正確的
STOR
命令(參見storbinary()
)。使用其readline()
方法從檔案物件 fp (以二進位模式打開)讀取各行、直到 EOF,以提供要儲存的資料。 callback 是可選的單參數可呼叫物件,於發送後以各行進行呼叫。
- transfercmd(cmd, rest=None)¶
通過資料連線啟動傳輸。如果傳輸為主動 (active) 模式,則發送
EPRT
或PORT
命令和 cmd 指定的傳輸命令,並接受連線。如果伺服器是被動 (passive) 模式,則發送EPSV
或PASV
命令、連線、並啟動傳輸命令。無論哪種方式,都是回傳連線的 socket。如果有給定可選的 rest,一個
REST
命令會被發送到伺服器,並以 rest 作為引數。rest 通常是請求檔案的一個位元組偏移量 (byte offset),告訴伺服器以請求的偏移量重新開始發送檔案的位元組,並跳過初始位元組。但是請注意,transfercmd()
方法將 rest 轉換為帶有初始化時指定的 encoding 參數的字串,但不會對字串的內容執行檢查。如果伺服器無法識別REST
命令,則會引發error_reply
例外。如果發生這種情況,只需在沒有 rest 引數的情況下呼叫transfercmd()
。
- ntransfercmd(cmd, rest=None)¶
類似於
transfercmd()
,但回傳一個帶有資料連線和資料預期大小的元組。如果無法計算預期大小,則回傳None
。 cmd 和 rest 與transfercmd()
中的含義相同。
- mlsd(path='', facts=[])¶
使用
MLSD
命令 (RFC 3659) 列出標準格式的目錄。如果省略 path 則假定為作用於當前目錄。facts 是表示所需資訊類型的字串列表(例如["type", "size", "perm"]
)。會回傳一個產生器物件,為每個在路徑中找到的檔案生成一個包含兩個元素的元組,第一個元素是檔案名稱,第二個元素是包含有關檔案名稱 facts的字典。該字典的內容可能受 facts 引數限制,但不保證伺服器會回傳所有請求的 facts。在 3.3 版新加入.
- nlst(argument[, ...])¶
回傳由
NLST
命令回傳的檔案名稱列表。可選的 argument 是要列出的目錄(預設為當前伺服器目錄)。多個引數可用於將非標準選項傳遞給NLST
命令。備註
如果你的伺服器支援該命令,
mlsd()
會提供更好的 API。
- dir(argument[, ...])¶
Produce a directory listing as returned by the
LIST
command, printing it to standard output. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to theLIST
command. If the last argument is a function, it is used as a callback function as forretrlines()
; the default prints tosys.stdout
. This method returnsNone
.備註
如果你的伺服器支援該命令,
mlsd()
會提供更好的 API。
- rename(fromname, toname)¶
將伺服器上的檔案 fromname 重新命名為 toname。
- delete(filename)¶
從伺服器中刪除名為 filename 的檔案。如果成功,回傳回應的文字,否則引發
error_perm
權限錯誤或在其他錯誤發生時引發error_reply
。
- cwd(pathname)¶
設定伺服器上的當前目錄。
- mkd(pathname)¶
在伺服器上建立一個新目錄。
- pwd()¶
回傳伺服器上當前目錄的路徑名。
- rmd(dirname)¶
刪除伺服器上名為 dirname 的目錄。
- size(filename)¶
請求伺服器上名為 filename 的檔案的大小。成功時,檔案的大小作為整數回傳,否則回傳
None
。請注意,SIZE
命令不是標準化的,但被許多常見的伺服器實作支援。
FTP_TLS objects¶
- class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8')¶
An
FTP
subclass which adds TLS support to FTP as described in RFC 4217. Connect to port 21 implicitly securing the FTP control connection before authenticating.備註
The user must explicitly secure the data connection by calling the
prot_p()
method.- 參數:
host (str) -- The hostname to connect to. If given,
connect(host)
is implicitly called by the constructor.user (str) -- The username to log in with (default:
'anonymous'
). If given,login(host, passwd, acct)
is implicitly called by the constructor.passwd (str) -- The password to use when logging in. If not given, and if passwd is the empty string or
"-"
, a password will be automatically generated.acct (str) -- Account information to be used for the
ACCT
FTP command. Few systems implement this. See RFC-959 for more details.context (
ssl.SSLContext
) -- An SSL context object which allows bundling SSL configuration options, certificates and private keys into a single, potentially long-lived, structure. Please read Security considerations for best practices.timeout (float | None) -- A timeout in seconds for blocking operations like
connect()
(default: the global default timeout setting).source_address (tuple | None) -- A 2-tuple
(host, port)
for the socket to bind to as its source address before connecting.encoding (str) -- The encoding for directories and filenames (default:
'utf-8'
).
keyfile 和 certfile 是 context 的傳統替代方案 -- 它們可以(分別)指向 SSL 連線的 PEM 格式私鑰和憑證鏈檔案。
在 3.2 版新加入.
在 3.3 版的變更: Added the source_address parameter.
在 3.4 版的變更: The class now supports hostname check with
ssl.SSLContext.check_hostname
and Server Name Indication (seessl.HAS_SNI
).在 3.6 版之後被棄用: keyfile 和 certfile 已棄用,取而代之的是 context。請改用
ssl.SSLContext.load_cert_chain()
,或讓ssl.create_default_context()
為你選擇系統的可信 CA 憑證。在 3.9 版的變更: 如果 timeout 參數設定為零,它將引發
ValueError
以防止建立非阻塞 socket。新增了 encoding 參數,預設值從 Latin-1 更改為 UTF-8 以遵循 RFC 2640。這是一個使用
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']
FTP_TLS
class inherits fromFTP
, defining these additional methods and attributes:- ssl_version¶
The SSL version to use (defaults to
ssl.PROTOCOL_SSLv23
).
- auth()¶
根據
ssl_version
屬性中指定的內容,使用 TLS 或 SSL 設定安全控制連線。在 3.4 版的變更: The method now supports hostname check with
ssl.SSLContext.check_hostname
and Server Name Indication (seessl.HAS_SNI
).
- ccc()¶
將控制通道恢復為純文本。這對於利用知道如何在不打開固定連接埠的情況下使用非安全 (non-secure) FTP 以處理 NAT 的防火牆很有用。
在 3.3 版新加入.
- prot_p()¶
設定安全資料連線。
- prot_c()¶
設定明文資料 (clear text data) 連線。
Module variables¶
- exception ftplib.error_reply¶
伺服器收到意外回覆時所引發的例外。
- exception ftplib.error_temp¶
當收到表示暫時錯誤的錯誤碼(400--499 範圍內的回應狀態碼)時引發的例外。
- exception ftplib.error_perm¶
當收到表示永久錯誤的錯誤碼(500--599 範圍內的回應狀態碼)時引發的例外。
- exception ftplib.error_proto¶
當從伺服器收到不符合檔案傳輸協定回應規範的回覆時引發例外,即 1--5 範圍內的數字開頭。
- ftplib.all_errors¶
FTP
實例方法由於 FTP 連線問題(相對於呼叫者的程式錯誤)而可能引發的所有例外集合(元組形式)。該集合包括上面列出的四個例外以及OSError
和EOFError
。
也參考
netrc
模組.netrc
檔案格式的剖析器。.netrc
檔案通常被 FTP 用戶端用來在提示使用者之前載入使用者身份驗證資訊。