• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`ftplib` --- FTP protocol client
2=====================================
3
4.. module:: ftplib
5   :synopsis: FTP protocol client (requires sockets).
6
7**Source code:** :source:`Lib/ftplib.py`
8
9.. index::
10   pair: FTP; protocol
11   single: FTP; ftplib (standard module)
12
13--------------
14
15This module defines the class :class:`FTP` and a few related items. The
16:class:`FTP` class implements the client side of the FTP protocol.  You can use
17this to write Python programs that perform a variety of automated FTP jobs, such
18as mirroring other FTP servers.  It is also used by the module
19:mod:`urllib.request` to handle URLs that use FTP.  For more information on FTP
20(File Transfer Protocol), see Internet :rfc:`959`.
21
22The default encoding is UTF-8, following :rfc:`2640`.
23
24Here's a sample session using the :mod:`ftplib` module::
25
26   >>> from ftplib import FTP
27   >>> ftp = FTP('ftp.us.debian.org')  # connect to host, default port
28   >>> ftp.login()                     # user anonymous, passwd anonymous@
29   '230 Login successful.'
30   >>> ftp.cwd('debian')               # change into "debian" directory
31   >>> ftp.retrlines('LIST')           # list directory contents
32   -rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
33   ...
34   drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
35   drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
36   drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
37   '226 Directory send OK.'
38   >>> with open('README', 'wb') as fp:
39   >>>     ftp.retrbinary('RETR README', fp.write)
40   '226 Transfer complete.'
41   >>> ftp.quit()
42
43
44The module defines the following items:
45
46.. class:: FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')
47
48   Return a new instance of the :class:`FTP` class.  When *host* is given, the
49   method call ``connect(host)`` is made.  When *user* is given, additionally
50   the method call ``login(user, passwd, acct)`` is made (where *passwd* and
51   *acct* default to the empty string when not given).  The optional *timeout*
52   parameter specifies a timeout in seconds for blocking operations like the
53   connection attempt (if is not specified, the global default timeout setting
54   will be used). *source_address* is a 2-tuple ``(host, port)`` for the socket
55   to bind to as its source address before connecting. The *encoding* parameter
56   specifies the encoding for directories and filenames.
57
58   The :class:`FTP` class supports the :keyword:`with` statement, e.g.:
59
60    >>> from ftplib import FTP
61    >>> with FTP("ftp1.at.proftpd.org") as ftp:
62    ...     ftp.login()
63    ...     ftp.dir()
64    ... # doctest: +SKIP
65    '230 Anonymous login ok, restrictions apply.'
66    dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
67    dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
68    dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
69    dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
70    >>>
71
72   .. versionchanged:: 3.2
73      Support for the :keyword:`with` statement was added.
74
75   .. versionchanged:: 3.3
76      *source_address* parameter was added.
77
78   .. versionchanged:: 3.9
79      If the *timeout* parameter is set to be zero, it will raise a
80      :class:`ValueError` to prevent the creation of a non-blocking socket.
81      The *encoding* parameter was added, and the default was changed from
82      Latin-1 to UTF-8 to follow :rfc:`2640`.
83
84.. class:: FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8')
85
86   A :class:`FTP` subclass which adds TLS support to FTP as described in
87   :rfc:`4217`.
88   Connect as usual to port 21 implicitly securing the FTP control connection
89   before authenticating. Securing the data connection requires the user to
90   explicitly ask for it by calling the :meth:`prot_p` method.  *context*
91   is a :class:`ssl.SSLContext` object which allows bundling SSL configuration
92   options, certificates and private keys into a single (potentially
93   long-lived) structure.  Please read :ref:`ssl-security` for best practices.
94
95   *keyfile* and *certfile* are a legacy alternative to *context* -- they
96   can point to PEM-formatted private key and certificate chain files
97   (respectively) for the SSL connection.
98
99   .. versionadded:: 3.2
100
101   .. versionchanged:: 3.3
102      *source_address* parameter was added.
103
104   .. versionchanged:: 3.4
105      The class now supports hostname check with
106      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
107      :data:`ssl.HAS_SNI`).
108
109   .. deprecated:: 3.6
110
111       *keyfile* and *certfile* are deprecated in favor of *context*.
112       Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
113       :func:`ssl.create_default_context` select the system's trusted CA
114       certificates for you.
115
116   .. versionchanged:: 3.9
117      If the *timeout* parameter is set to be zero, it will raise a
118      :class:`ValueError` to prevent the creation of a non-blocking socket.
119      The *encoding* parameter was added, and the default was changed from
120      Latin-1 to UTF-8 to follow :rfc:`2640`.
121
122   Here's a sample session using the :class:`FTP_TLS` class::
123
124      >>> ftps = FTP_TLS('ftp.pureftpd.org')
125      >>> ftps.login()
126      '230 Anonymous user logged in'
127      >>> ftps.prot_p()
128      '200 Data protection level set to "private"'
129      >>> ftps.nlst()
130      ['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']
131
132
133.. exception:: error_reply
134
135   Exception raised when an unexpected reply is received from the server.
136
137
138.. exception:: error_temp
139
140   Exception raised when an error code signifying a temporary error (response
141   codes in the range 400--499) is received.
142
143
144.. exception:: error_perm
145
146   Exception raised when an error code signifying a permanent error (response
147   codes in the range 500--599) is received.
148
149
150.. exception:: error_proto
151
152   Exception raised when a reply is received from the server that does not fit
153   the response specifications of the File Transfer Protocol, i.e. begin with a
154   digit in the range 1--5.
155
156
157.. data:: all_errors
158
159   The set of all exceptions (as a tuple) that methods of :class:`FTP`
160   instances may raise as a result of problems with the FTP connection (as
161   opposed to programming errors made by the caller).  This set includes the
162   four exceptions listed above as well as :exc:`OSError` and :exc:`EOFError`.
163
164
165.. seealso::
166
167   Module :mod:`netrc`
168      Parser for the :file:`.netrc` file format.  The file :file:`.netrc` is
169      typically used by FTP clients to load user authentication information
170      before prompting the user.
171
172
173.. _ftp-objects:
174
175FTP Objects
176-----------
177
178Several methods are available in two flavors: one for handling text files and
179another for binary files.  These are named for the command which is used
180followed by ``lines`` for the text version or ``binary`` for the binary version.
181
182:class:`FTP` instances have the following methods:
183
184
185.. method:: FTP.set_debuglevel(level)
186
187   Set the instance's debugging level.  This controls the amount of debugging
188   output printed.  The default, ``0``, produces no debugging output.  A value of
189   ``1`` produces a moderate amount of debugging output, generally a single line
190   per request.  A value of ``2`` or higher produces the maximum amount of
191   debugging output, logging each line sent and received on the control connection.
192
193
194.. method:: FTP.connect(host='', port=0, timeout=None, source_address=None)
195
196   Connect to the given host and port.  The default port number is ``21``, as
197   specified by the FTP protocol specification.  It is rarely needed to specify a
198   different port number.  This function should be called only once for each
199   instance; it should not be called at all if a host was given when the instance
200   was created.  All other methods can only be used after a connection has been
201   made.
202   The optional *timeout* parameter specifies a timeout in seconds for the
203   connection attempt. If no *timeout* is passed, the global default timeout
204   setting will be used.
205   *source_address* is a 2-tuple ``(host, port)`` for the socket to bind to as
206   its source address before connecting.
207
208   .. audit-event:: ftplib.connect self,host,port ftplib.FTP.connect
209
210   .. versionchanged:: 3.3
211      *source_address* parameter was added.
212
213
214.. method:: FTP.getwelcome()
215
216   Return the welcome message sent by the server in reply to the initial
217   connection.  (This message sometimes contains disclaimers or help information
218   that may be relevant to the user.)
219
220
221.. method:: FTP.login(user='anonymous', passwd='', acct='')
222
223   Log in as the given *user*.  The *passwd* and *acct* parameters are optional and
224   default to the empty string.  If no *user* is specified, it defaults to
225   ``'anonymous'``.  If *user* is ``'anonymous'``, the default *passwd* is
226   ``'anonymous@'``.  This function should be called only once for each instance,
227   after a connection has been established; it should not be called at all if a
228   host and user were given when the instance was created.  Most FTP commands are
229   only allowed after the client has logged in.  The *acct* parameter supplies
230   "accounting information"; few systems implement this.
231
232
233.. method:: FTP.abort()
234
235   Abort a file transfer that is in progress.  Using this does not always work, but
236   it's worth a try.
237
238
239.. method:: FTP.sendcmd(cmd)
240
241   Send a simple command string to the server and return the response string.
242
243   .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.sendcmd
244
245
246.. method:: FTP.voidcmd(cmd)
247
248   Send a simple command string to the server and handle the response.  Return
249   nothing if a response code corresponding to success (codes in the range
250   200--299) is received.  Raise :exc:`error_reply` otherwise.
251
252   .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.voidcmd
253
254
255.. method:: FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)
256
257   Retrieve a file in binary transfer mode.  *cmd* should be an appropriate
258   ``RETR`` command: ``'RETR filename'``. The *callback* function is called for
259   each block of data received, with a single bytes argument giving the data
260   block. The optional *blocksize* argument specifies the maximum chunk size to
261   read on the low-level socket object created to do the actual transfer (which
262   will also be the largest size of the data blocks passed to *callback*).  A
263   reasonable default is chosen. *rest* means the same thing as in the
264   :meth:`transfercmd` method.
265
266
267.. method:: FTP.retrlines(cmd, callback=None)
268
269   Retrieve a file or directory listing in the encoding specified by the
270   *encoding* parameter at initialization.
271   *cmd* should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or
272   a command such as ``LIST`` or ``NLST`` (usually just the string ``'LIST'``).
273   ``LIST`` retrieves a list of files and information about those files.
274   ``NLST`` retrieves a list of file names.
275   The *callback* function is called for each line with a string argument
276   containing the line with the trailing CRLF stripped.  The default *callback*
277   prints the line to ``sys.stdout``.
278
279
280.. method:: FTP.set_pasv(val)
281
282   Enable "passive" mode if *val* is true, otherwise disable passive mode.
283   Passive mode is on by default.
284
285
286.. method:: FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)
287
288   Store a file in binary transfer mode.  *cmd* should be an appropriate
289   ``STOR`` command: ``"STOR filename"``. *fp* is a :term:`file object`
290   (opened in binary mode) which is read until EOF using its :meth:`~io.IOBase.read`
291   method in blocks of size *blocksize* to provide the data to be stored.
292   The *blocksize* argument defaults to 8192.  *callback* is an optional single
293   parameter callable that is called on each block of data after it is sent.
294   *rest* means the same thing as in the :meth:`transfercmd` method.
295
296   .. versionchanged:: 3.2
297      *rest* parameter added.
298
299
300.. method:: FTP.storlines(cmd, fp, callback=None)
301
302   Store a file in line mode.  *cmd* should be an appropriate
303   ``STOR`` command (see :meth:`storbinary`).  Lines are read until EOF from the
304   :term:`file object` *fp* (opened in binary mode) using its :meth:`~io.IOBase.readline`
305   method to provide the data to be stored.  *callback* is an optional single
306   parameter callable that is called on each line after it is sent.
307
308
309.. method:: FTP.transfercmd(cmd, rest=None)
310
311   Initiate a transfer over the data connection.  If the transfer is active, send an
312   ``EPRT`` or  ``PORT`` command and the transfer command specified by *cmd*, and
313   accept the connection.  If the server is passive, send an ``EPSV`` or ``PASV``
314   command, connect to it, and start the transfer command.  Either way, return the
315   socket for the connection.
316
317   If optional *rest* is given, a ``REST`` command is sent to the server, passing
318   *rest* as an argument.  *rest* is usually a byte offset into the requested file,
319   telling the server to restart sending the file's bytes at the requested offset,
320   skipping over the initial bytes.  Note however that the :meth:`transfercmd`
321   method converts *rest* to a string with the *encoding* parameter specified
322   at initialization, but no check is performed on the string's contents.  If the
323   server does not recognize the ``REST`` command, an :exc:`error_reply` exception
324   will be raised.  If this happens, simply call :meth:`transfercmd` without a
325   *rest* argument.
326
327
328.. method:: FTP.ntransfercmd(cmd, rest=None)
329
330   Like :meth:`transfercmd`, but returns a tuple of the data connection and the
331   expected size of the data.  If the expected size could not be computed, ``None``
332   will be returned as the expected size.  *cmd* and *rest* means the same thing as
333   in :meth:`transfercmd`.
334
335
336.. method:: FTP.mlsd(path="", facts=[])
337
338   List a directory in a standardized format by using ``MLSD`` command
339   (:rfc:`3659`).  If *path* is omitted the current directory is assumed.
340   *facts* is a list of strings representing the type of information desired
341   (e.g. ``["type", "size", "perm"]``).  Return a generator object yielding a
342   tuple of two elements for every file found in path.  First element is the
343   file name, the second one is a dictionary containing facts about the file
344   name.  Content of this dictionary might be limited by the *facts* argument
345   but server is not guaranteed to return all requested facts.
346
347   .. versionadded:: 3.3
348
349
350.. method:: FTP.nlst(argument[, ...])
351
352   Return a list of file names as returned by the ``NLST`` command.  The
353   optional *argument* is a directory to list (default is the current server
354   directory).  Multiple arguments can be used to pass non-standard options to
355   the ``NLST`` command.
356
357   .. note:: If your server supports the command, :meth:`mlsd` offers a better API.
358
359
360.. method:: FTP.dir(argument[, ...])
361
362   Produce a directory listing as returned by the ``LIST`` command, printing it to
363   standard output.  The optional *argument* is a directory to list (default is the
364   current server directory).  Multiple arguments can be used to pass non-standard
365   options to the ``LIST`` command.  If the last argument is a function, it is used
366   as a *callback* function as for :meth:`retrlines`; the default prints to
367   ``sys.stdout``.  This method returns ``None``.
368
369   .. note:: If your server supports the command, :meth:`mlsd` offers a better API.
370
371
372.. method:: FTP.rename(fromname, toname)
373
374   Rename file *fromname* on the server to *toname*.
375
376
377.. method:: FTP.delete(filename)
378
379   Remove the file named *filename* from the server.  If successful, returns the
380   text of the response, otherwise raises :exc:`error_perm` on permission errors or
381   :exc:`error_reply` on other errors.
382
383
384.. method:: FTP.cwd(pathname)
385
386   Set the current directory on the server.
387
388
389.. method:: FTP.mkd(pathname)
390
391   Create a new directory on the server.
392
393
394.. method:: FTP.pwd()
395
396   Return the pathname of the current directory on the server.
397
398
399.. method:: FTP.rmd(dirname)
400
401   Remove the directory named *dirname* on the server.
402
403
404.. method:: FTP.size(filename)
405
406   Request the size of the file named *filename* on the server.  On success, the
407   size of the file is returned as an integer, otherwise ``None`` is returned.
408   Note that the ``SIZE`` command is not  standardized, but is supported by many
409   common server implementations.
410
411
412.. method:: FTP.quit()
413
414   Send a ``QUIT`` command to the server and close the connection. This is the
415   "polite" way to close a connection, but it may raise an exception if the server
416   responds with an error to the ``QUIT`` command.  This implies a call to the
417   :meth:`close` method which renders the :class:`FTP` instance useless for
418   subsequent calls (see below).
419
420
421.. method:: FTP.close()
422
423   Close the connection unilaterally.  This should not be applied to an already
424   closed connection such as after a successful call to :meth:`~FTP.quit`.
425   After this call the :class:`FTP` instance should not be used any more (after
426   a call to :meth:`close` or :meth:`~FTP.quit` you cannot reopen the
427   connection by issuing another :meth:`login` method).
428
429
430FTP_TLS Objects
431---------------
432
433:class:`FTP_TLS` class inherits from :class:`FTP`, defining these additional objects:
434
435.. attribute:: FTP_TLS.ssl_version
436
437   The SSL version to use (defaults to :attr:`ssl.PROTOCOL_SSLv23`).
438
439.. method:: FTP_TLS.auth()
440
441   Set up a secure control connection by using TLS or SSL, depending on what
442   is specified in the :attr:`ssl_version` attribute.
443
444   .. versionchanged:: 3.4
445      The method now supports hostname check with
446      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
447      :data:`ssl.HAS_SNI`).
448
449.. method:: FTP_TLS.ccc()
450
451   Revert control channel back to plaintext.  This can be useful to take
452   advantage of firewalls that know how to handle NAT with non-secure FTP
453   without opening fixed ports.
454
455   .. versionadded:: 3.3
456
457.. method:: FTP_TLS.prot_p()
458
459   Set up secure data connection.
460
461.. method:: FTP_TLS.prot_c()
462
463   Set up clear text data connection.
464