• 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
24.. include:: ../includes/wasm-notavail.rst
25
26Here's a sample session using the :mod:`ftplib` module::
27
28   >>> from ftplib import FTP
29   >>> ftp = FTP('ftp.us.debian.org')  # connect to host, default port
30   >>> ftp.login()                     # user anonymous, passwd anonymous@
31   '230 Login successful.'
32   >>> ftp.cwd('debian')               # change into "debian" directory
33   '250 Directory successfully changed.'
34   >>> ftp.retrlines('LIST')           # list directory contents
35   -rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
36   ...
37   drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
38   drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
39   drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
40   '226 Directory send OK.'
41   >>> with open('README', 'wb') as fp:
42   >>>     ftp.retrbinary('RETR README', fp.write)
43   '226 Transfer complete.'
44   >>> ftp.quit()
45   '221 Goodbye.'
46
47
48.. _ftplib-reference:
49
50Reference
51---------
52
53.. _ftp-objects:
54
55FTP objects
56^^^^^^^^^^^
57
58.. Use substitutions for some param docs so we don't need to repeat them
59   in multiple places.
60
61.. |param_doc_user| replace::
62   The username to log in with (default: ``'anonymous'``).
63
64.. |param_doc_passwd| replace::
65   The password to use when logging in.
66   If not given, and if *passwd* is the empty string or ``"-"``,
67   a password will be automatically generated.
68
69.. Ideally, we'd like to use the :rfc: directive, but Sphinx will not allow it.
70
71.. |param_doc_acct| replace::
72   Account information to be used for the ``ACCT`` FTP command.
73   Few systems implement this.
74   See `RFC-959 <https://datatracker.ietf.org/doc/html/rfc959.html>`__
75   for more details.
76
77.. |param_doc_source_address| replace::
78   A 2-tuple ``(host, port)`` for the socket to bind to as its
79   source address before connecting.
80
81.. |param_doc_encoding| replace::
82   The encoding for directories and filenames (default: ``'utf-8'``).
83
84.. class:: FTP(host='', user='', passwd='', acct='', timeout=None, \
85               source_address=None, *, encoding='utf-8')
86
87   Return a new instance of the :class:`FTP` class.
88
89   :param str host:
90      The hostname to connect to.
91      If given, :code:`connect(host)` is implicitly called by the constructor.
92
93   :param str user:
94      |param_doc_user|
95      If given, :code:`login(host, passwd, acct)` is implicitly called
96      by the constructor.
97
98   :param str passwd:
99      |param_doc_passwd|
100
101   :param str acct:
102      |param_doc_acct|
103
104   :param timeout:
105      A timeout in seconds for blocking operations like :meth:`connect`
106      (default: the global default timeout setting).
107   :type timeout: float | None
108
109   :param source_address:
110      |param_doc_source_address|
111   :type source_address: tuple | None
112
113   :param str encoding:
114      |param_doc_encoding|
115
116   The :class:`FTP` class supports the :keyword:`with` statement, e.g.:
117
118    >>> from ftplib import FTP
119    >>> with FTP("ftp1.at.proftpd.org") as ftp:
120    ...     ftp.login()
121    ...     ftp.dir()
122    ... # doctest: +SKIP
123    '230 Anonymous login ok, restrictions apply.'
124    dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
125    dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
126    dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
127    dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
128    >>>
129
130   .. versionchanged:: 3.2
131      Support for the :keyword:`with` statement was added.
132
133   .. versionchanged:: 3.3
134      *source_address* parameter was added.
135
136   .. versionchanged:: 3.9
137      If the *timeout* parameter is set to be zero, it will raise a
138      :class:`ValueError` to prevent the creation of a non-blocking socket.
139      The *encoding* parameter was added, and the default was changed from
140      Latin-1 to UTF-8 to follow :rfc:`2640`.
141
142   Several :class:`!FTP` methods are available in two flavors:
143   one for handling text files and another for binary files.
144   The methods are named for the command which is used followed by
145   ``lines`` for the text version or ``binary`` for the binary version.
146
147   :class:`FTP` instances have the following methods:
148
149   .. method:: FTP.set_debuglevel(level)
150
151      Set the instance's debugging level as an :class:`int`.
152      This controls the amount of debugging output printed.
153      The debug levels are:
154
155      * ``0`` (default): No debug output.
156      * ``1``: Produce a moderate amount of debug output,
157        generally a single line per request.
158      * ``2`` or higher: Produce the maximum amount of debugging output,
159        logging each line sent and received on the control connection.
160
161   .. method:: FTP.connect(host='', port=0, timeout=None, source_address=None)
162
163      Connect to the given host and port.
164      This function should be called only once for each instance;
165      it should not be called if a *host* argument was given
166      when the :class:`FTP` instance was created.
167      All other :class:`!FTP` methods can only be called
168      after a connection has successfully been made.
169
170      :param str host:
171         The host to connect to.
172
173      :param int port:
174         The TCP port to connect to (default: ``21``,
175         as specified by the FTP protocol specification).
176         It is rarely needed to specify a different port number.
177
178      :param timeout:
179         A timeout in seconds for the connection attempt
180         (default: the global default timeout setting).
181      :type timeout: float | None
182
183      :param source_address:
184         |param_doc_source_address|
185      :type source_address: tuple | None
186
187      .. audit-event:: ftplib.connect self,host,port ftplib.FTP.connect
188
189      .. versionchanged:: 3.3
190         *source_address* parameter was added.
191
192
193   .. method:: FTP.getwelcome()
194
195      Return the welcome message sent by the server in reply to the initial
196      connection.  (This message sometimes contains disclaimers or help information
197      that may be relevant to the user.)
198
199
200   .. method:: FTP.login(user='anonymous', passwd='', acct='')
201
202      Log on to the connected FTP server.
203      This function should be called only once for each instance,
204      after a connection has been established;
205      it should not be called if the *host* and *user* arguments were given
206      when the :class:`FTP` instance was created.
207      Most FTP commands are only allowed after the client has logged in.
208
209      :param str user:
210         |param_doc_user|
211
212      :param str passwd:
213         |param_doc_passwd|
214
215      :param str acct:
216         |param_doc_acct|
217
218
219   .. method:: FTP.abort()
220
221      Abort a file transfer that is in progress.  Using this does not always work, but
222      it's worth a try.
223
224
225   .. method:: FTP.sendcmd(cmd)
226
227      Send a simple command string to the server and return the response string.
228
229      .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.sendcmd
230
231
232   .. method:: FTP.voidcmd(cmd)
233
234      Send a simple command string to the server and handle the response.  Return
235      the response string if the response code corresponds to success (codes in
236      the range 200--299).  Raise :exc:`error_reply` otherwise.
237
238      .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.voidcmd
239
240
241   .. method:: FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)
242
243      Retrieve a file in binary transfer mode.
244
245      :param str cmd:
246        An appropriate ``RETR`` command: :samp:`"RETR {filename}"`.
247
248      :param callback:
249         A single parameter callable that is called
250         for each block of data received,
251         with its single argument being the data as :class:`bytes`.
252      :type callback: :term:`callable`
253
254      :param int blocksize:
255         The maximum chunk size to read on the low-level
256         :class:`~socket.socket` object created to do the actual transfer.
257         This also corresponds to the largest size of data
258         that will be passed to *callback*.
259         Defaults to ``8192``.
260
261      :param int rest:
262         A ``REST`` command to be sent to the server.
263         See the documentation for the *rest* parameter of the :meth:`transfercmd` method.
264
265
266   .. method:: FTP.retrlines(cmd, callback=None)
267
268      Retrieve a file or directory listing in the encoding specified by the
269      *encoding* parameter at initialization.
270      *cmd* should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or
271      a command such as ``LIST`` or ``NLST`` (usually just the string ``'LIST'``).
272      ``LIST`` retrieves a list of files and information about those files.
273      ``NLST`` retrieves a list of file names.
274      The *callback* function is called for each line with a string argument
275      containing the line with the trailing CRLF stripped.  The default *callback*
276      prints the line to :data:`sys.stdout`.
277
278
279   .. method:: FTP.set_pasv(val)
280
281      Enable "passive" mode if *val* is true, otherwise disable passive mode.
282      Passive mode is on by default.
283
284
285   .. method:: FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)
286
287      Store a file in binary transfer mode.
288
289      :param str cmd:
290        An appropriate ``STOR`` command: :samp:`"STOR {filename}"`.
291
292      :param fp:
293         A file object (opened in binary mode) which is read until EOF,
294         using its :meth:`~io.RawIOBase.read` method in blocks of size *blocksize*
295         to provide the data to be stored.
296      :type fp: :term:`file object`
297
298      :param int blocksize:
299         The read block size.
300         Defaults to ``8192``.
301
302      :param callback:
303         A single parameter callable that is called
304         for each block of data sent,
305         with its single argument being the data as :class:`bytes`.
306      :type callback: :term:`callable`
307
308      :param int rest:
309         A ``REST`` command to be sent to the server.
310         See the documentation for the *rest* parameter of the :meth:`transfercmd` method.
311
312      .. versionchanged:: 3.2
313         The *rest* parameter was added.
314
315
316   .. method:: FTP.storlines(cmd, fp, callback=None)
317
318      Store a file in line mode.  *cmd* should be an appropriate
319      ``STOR`` command (see :meth:`storbinary`).  Lines are read until EOF from the
320      :term:`file object` *fp* (opened in binary mode) using its :meth:`~io.IOBase.readline`
321      method to provide the data to be stored.  *callback* is an optional single
322      parameter callable that is called on each line after it is sent.
323
324
325   .. method:: FTP.transfercmd(cmd, rest=None)
326
327      Initiate a transfer over the data connection.  If the transfer is active, send an
328      ``EPRT`` or  ``PORT`` command and the transfer command specified by *cmd*, and
329      accept the connection.  If the server is passive, send an ``EPSV`` or ``PASV``
330      command, connect to it, and start the transfer command.  Either way, return the
331      socket for the connection.
332
333      If optional *rest* is given, a ``REST`` command is sent to the server, passing
334      *rest* as an argument.  *rest* is usually a byte offset into the requested file,
335      telling the server to restart sending the file's bytes at the requested offset,
336      skipping over the initial bytes.  Note however that the :meth:`transfercmd`
337      method converts *rest* to a string with the *encoding* parameter specified
338      at initialization, but no check is performed on the string's contents.  If the
339      server does not recognize the ``REST`` command, an :exc:`error_reply` exception
340      will be raised.  If this happens, simply call :meth:`transfercmd` without a
341      *rest* argument.
342
343
344   .. method:: FTP.ntransfercmd(cmd, rest=None)
345
346      Like :meth:`transfercmd`, but returns a tuple of the data connection and the
347      expected size of the data.  If the expected size could not be computed, ``None``
348      will be returned as the expected size.  *cmd* and *rest* means the same thing as
349      in :meth:`transfercmd`.
350
351
352   .. method:: FTP.mlsd(path="", facts=[])
353
354      List a directory in a standardized format by using ``MLSD`` command
355      (:rfc:`3659`).  If *path* is omitted the current directory is assumed.
356      *facts* is a list of strings representing the type of information desired
357      (e.g. ``["type", "size", "perm"]``).  Return a generator object yielding a
358      tuple of two elements for every file found in path.  First element is the
359      file name, the second one is a dictionary containing facts about the file
360      name.  Content of this dictionary might be limited by the *facts* argument
361      but server is not guaranteed to return all requested facts.
362
363      .. versionadded:: 3.3
364
365
366   .. method:: FTP.nlst(argument[, ...])
367
368      Return a list of file names as returned by the ``NLST`` command.  The
369      optional *argument* is a directory to list (default is the current server
370      directory).  Multiple arguments can be used to pass non-standard options to
371      the ``NLST`` command.
372
373      .. note:: If your server supports the command, :meth:`mlsd` offers a better API.
374
375
376   .. method:: FTP.dir(argument[, ...])
377
378      Produce a directory listing as returned by the ``LIST`` command, printing it to
379      standard output.  The optional *argument* is a directory to list (default is the
380      current server directory).  Multiple arguments can be used to pass non-standard
381      options to the ``LIST`` command.  If the last argument is a function, it is used
382      as a *callback* function as for :meth:`retrlines`; the default prints to
383      :data:`sys.stdout`.  This method returns ``None``.
384
385      .. note:: If your server supports the command, :meth:`mlsd` offers a better API.
386
387
388   .. method:: FTP.rename(fromname, toname)
389
390      Rename file *fromname* on the server to *toname*.
391
392
393   .. method:: FTP.delete(filename)
394
395      Remove the file named *filename* from the server.  If successful, returns the
396      text of the response, otherwise raises :exc:`error_perm` on permission errors or
397      :exc:`error_reply` on other errors.
398
399
400   .. method:: FTP.cwd(pathname)
401
402      Set the current directory on the server.
403
404
405   .. method:: FTP.mkd(pathname)
406
407      Create a new directory on the server.
408
409
410   .. method:: FTP.pwd()
411
412      Return the pathname of the current directory on the server.
413
414
415   .. method:: FTP.rmd(dirname)
416
417      Remove the directory named *dirname* on the server.
418
419
420   .. method:: FTP.size(filename)
421
422      Request the size of the file named *filename* on the server.  On success, the
423      size of the file is returned as an integer, otherwise ``None`` is returned.
424      Note that the ``SIZE`` command is not  standardized, but is supported by many
425      common server implementations.
426
427
428   .. method:: FTP.quit()
429
430      Send a ``QUIT`` command to the server and close the connection. This is the
431      "polite" way to close a connection, but it may raise an exception if the server
432      responds with an error to the ``QUIT`` command.  This implies a call to the
433      :meth:`close` method which renders the :class:`FTP` instance useless for
434      subsequent calls (see below).
435
436
437   .. method:: FTP.close()
438
439      Close the connection unilaterally.  This should not be applied to an already
440      closed connection such as after a successful call to :meth:`~FTP.quit`.
441      After this call the :class:`FTP` instance should not be used any more (after
442      a call to :meth:`close` or :meth:`~FTP.quit` you cannot reopen the
443      connection by issuing another :meth:`login` method).
444
445
446FTP_TLS objects
447^^^^^^^^^^^^^^^
448
449.. class:: FTP_TLS(host='', user='', passwd='', acct='', *, context=None, \
450                   timeout=None, source_address=None, encoding='utf-8')
451
452   An :class:`FTP` subclass which adds TLS support to FTP as described in
453   :rfc:`4217`.
454   Connect to port 21 implicitly securing the FTP control connection
455   before authenticating.
456
457   .. note::
458      The user must explicitly secure the data connection
459      by calling the :meth:`prot_p` method.
460
461   :param str host:
462      The hostname to connect to.
463      If given, :code:`connect(host)` is implicitly called by the constructor.
464
465   :param str user:
466      |param_doc_user|
467      If given, :code:`login(host, passwd, acct)` is implicitly called
468      by the constructor.
469
470   :param str passwd:
471      |param_doc_passwd|
472
473   :param str acct:
474      |param_doc_acct|
475
476   :param context:
477      An SSL context object which allows bundling SSL configuration options,
478      certificates and private keys into a single, potentially long-lived,
479      structure.
480      Please read :ref:`ssl-security` for best practices.
481   :type context: :class:`ssl.SSLContext`
482
483   :param timeout:
484      A timeout in seconds for blocking operations like :meth:`~FTP.connect`
485      (default: the global default timeout setting).
486   :type timeout: float | None
487
488   :param source_address:
489      |param_doc_source_address|
490   :type source_address: tuple | None
491
492   :param str encoding:
493      |param_doc_encoding|
494
495   .. versionadded:: 3.2
496
497   .. versionchanged:: 3.3
498      Added the *source_address* parameter.
499
500   .. versionchanged:: 3.4
501      The class now supports hostname check with
502      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
503      :const:`ssl.HAS_SNI`).
504
505   .. versionchanged:: 3.9
506      If the *timeout* parameter is set to be zero, it will raise a
507      :class:`ValueError` to prevent the creation of a non-blocking socket.
508      The *encoding* parameter was added, and the default was changed from
509      Latin-1 to UTF-8 to follow :rfc:`2640`.
510
511   .. versionchanged:: 3.12
512      The deprecated *keyfile* and *certfile* parameters have been removed.
513
514   Here's a sample session using the :class:`FTP_TLS` class::
515
516      >>> ftps = FTP_TLS('ftp.pureftpd.org')
517      >>> ftps.login()
518      '230 Anonymous user logged in'
519      >>> ftps.prot_p()
520      '200 Data protection level set to "private"'
521      >>> ftps.nlst()
522      ['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']
523
524   :class:`!FTP_TLS` class inherits from :class:`FTP`,
525   defining these additional methods and attributes:
526
527   .. attribute:: FTP_TLS.ssl_version
528
529      The SSL version to use (defaults to :data:`ssl.PROTOCOL_SSLv23`).
530
531   .. method:: FTP_TLS.auth()
532
533      Set up a secure control connection by using TLS or SSL, depending on what
534      is specified in the :attr:`ssl_version` attribute.
535
536      .. versionchanged:: 3.4
537         The method now supports hostname check with
538         :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
539         :const:`ssl.HAS_SNI`).
540
541   .. method:: FTP_TLS.ccc()
542
543      Revert control channel back to plaintext.  This can be useful to take
544      advantage of firewalls that know how to handle NAT with non-secure FTP
545      without opening fixed ports.
546
547      .. versionadded:: 3.3
548
549   .. method:: FTP_TLS.prot_p()
550
551      Set up secure data connection.
552
553   .. method:: FTP_TLS.prot_c()
554
555      Set up clear text data connection.
556
557
558Module variables
559^^^^^^^^^^^^^^^^
560
561.. exception:: error_reply
562
563   Exception raised when an unexpected reply is received from the server.
564
565
566.. exception:: error_temp
567
568   Exception raised when an error code signifying a temporary error (response
569   codes in the range 400--499) is received.
570
571
572.. exception:: error_perm
573
574   Exception raised when an error code signifying a permanent error (response
575   codes in the range 500--599) is received.
576
577
578.. exception:: error_proto
579
580   Exception raised when a reply is received from the server that does not fit
581   the response specifications of the File Transfer Protocol, i.e. begin with a
582   digit in the range 1--5.
583
584
585.. data:: all_errors
586
587   The set of all exceptions (as a tuple) that methods of :class:`FTP`
588   instances may raise as a result of problems with the FTP connection (as
589   opposed to programming errors made by the caller).  This set includes the
590   four exceptions listed above as well as :exc:`OSError` and :exc:`EOFError`.
591
592
593.. seealso::
594
595   Module :mod:`netrc`
596      Parser for the :file:`.netrc` file format.  The file :file:`.netrc` is
597      typically used by FTP clients to load user authentication information
598      before prompting the user.
599