ftplib — FTP protocol client

Вихідний код: Lib/ftplib.py


This module defines the class FTP and a few related items. The FTP class implements the client side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers. It is also used by the module urllib.request to handle URLs that use FTP. For more information on FTP (File Transfer Protocol), see 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()

The module defines the following items:

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)

A FTP subclass which adds TLS support to FTP as described in RFC 4217. Connect as usual to port 21 implicitly securing the FTP control connection before authenticating. Securing the data connection requires the user to explicitly ask for it by calling the prot_p() method. context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Міркування безпеки for best practices.

keyfile and certfile are a legacy alternative to context – they can point to PEM-formatted private key and certificate chain files (respectively) for the SSL connection.

Нове в версії 3.2.

Змінено в версії 3.3: Додано параметр source_address.

Змінено в версії 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

Застаріло починаючи з версії 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

Ось зразок сеансу з використанням класу 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

Виняток виникає, коли відповідь, отримана від сервера, не відповідає специфікаціям відповіді протоколу передачі файлів, тобто починається з цифри в діапазоні 1–5.

ftplib.all_errors

Набір усіх винятків (у вигляді кортежу), які методи екземплярів FTP можуть викликати в результаті проблем із з’єднанням FTP (на відміну від програмних помилок, зроблених абонентом). Цей набір включає чотири винятки, перелічені вище, а також OSError і EOFError.

Дивись також

Модуль netrc

Парсер для формату файлу .netrc. Файл .netrc зазвичай використовується FTP-клієнтами для завантаження інформації про автентифікацію користувача перед запитом користувача.

FTP Objects

Several methods are available in two flavors: one for handling text files and another for binary files. These are named for the command which is used followed by lines for the text version or binary for the binary version.

Екземпляри FTP мають такі методи:

FTP.set_debuglevel(level)

Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection.

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

Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, 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.

Викликає подію аудиту ftplib.connect з аргументами self, host, port.

Змінено в версії 3.3: Додано параметр source_address.

FTP.getwelcome()

Повернути вітальне повідомлення, надіслане сервером у відповідь на початкове підключення. (Це повідомлення іноді містить застереження або довідкову інформацію, яка може бути актуальною для користувача.)

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

Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'. This function should be called only once for each instance, after a connection has been established; it should not be called at all if a host and user were given when the instance was created. Most FTP commands are only allowed after the client has logged in. The acct parameter supplies «accounting information»; few systems implement this.

FTP.abort()

Перервати передачу файлу, що триває. Використання цього не завжди працює, але варто спробувати.

FTP.sendcmd(cmd)

Надішліть простий рядок команди на сервер і поверніть рядок відповіді.

Викликає подію аудиту ftplib.sendcmd з аргументами self, cmd.

FTP.voidcmd(cmd)

Send a simple command string to the server and handle the response. Return nothing if a response code corresponding to success (codes in the range 200–299) is received. Raise error_reply otherwise.

Викликає подію аудиту ftplib.sendcmd з аргументами self, cmd.

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

Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'. The callback function is called for each block of data received, with a single bytes argument giving the data block. The optional blocksize argument specifies the maximum chunk size to read on the low-level socket object created to do the actual transfer (which will also be the largest size of the data blocks passed to callback). A reasonable default is chosen. rest means the same thing as in the transfercmd() method.

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)

Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". fp is 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. The blocksize argument defaults to 8192. callback is an optional single parameter callable that is called on each block of data after it is sent. rest means the same thing as in the transfercmd() method.

Змінено в версії 3.2: rest parameter added.

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)

Ініціювати передачу через з’єднання даних. Якщо передача активна, надішліть команду EPRT або PORT і команду передачі, визначену cmd, і прийміть з’єднання. Якщо сервер пасивний, надішліть команду EPSV або PASV, підключіться до нього та запустіть команду передачі. У будь-якому випадку поверніть розетку для підключення.

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(), але повертає кортеж з’єднання даних і очікуваний розмір даних. Якщо очікуваний розмір не вдалося обчислити, як очікуваний розмір буде повернено «Немає». cmd і rest означають те саме, що й у transfercmd().

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

Перерахуйте каталог у стандартизованому форматі за допомогою команди MLSD (RFC 3659). Якщо шлях опущено, передбачається поточний каталог. факти — це список рядків, що представляють тип бажаної інформації (наприклад, ["тип", "розмір", "перм"]). Повертає об’єкт-генератор, утворюючи кортеж із двох елементів для кожного файлу, знайденого на шляху. Перший елемент – ім’я файлу, другий – словник, що містить інформацію про ім’я файлу. Вміст цього словника може бути обмежений аргументом факти, але сервер не гарантує повернення всіх запитуваних фактів.

Нове в версії 3.3.

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

Повертає список імен файлів, які повертає команда NLST. Необов’язковий аргумент — це каталог для переліку (за замовчуванням — це поточний каталог сервера). Для передачі нестандартних параметрів команді NLST можна використовувати кілька аргументів.

Примітка

Якщо ваш сервер підтримує команду, mlsd() пропонує кращий API.

FTP.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 the LIST command. If the last argument is a function, it is used as a callback function as for retrlines(); the default prints to sys.stdout. This method returns 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 Objects

FTP_TLS class inherits from FTP, defining these additional objects:

FTP_TLS.ssl_version

The SSL version to use (defaults to ssl.PROTOCOL_SSLv23).

FTP_TLS.auth()

Налаштуйте безпечне контрольне з’єднання за допомогою TLS або SSL, залежно від того, що вказано в атрибуті ssl_version.

Змінено в версії 3.4: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

FTP_TLS.ccc()

Повернути канал керування назад до відкритого тексту. Це може бути корисним, щоб скористатися перевагами брандмауерів, які знають, як обробляти NAT із незахищеним FTP без відкриття фіксованих портів.

Нове в версії 3.3.

FTP_TLS.prot_p()

Налаштуйте безпечне з’єднання даних.

FTP_TLS.prot_c()

Налаштуйте підключення для передачі даних у відкритому тексті.