Ftplib error temp

FTP or File Transfer Protocol is a common way to transfer files. For FTP, Python has a built in package called [ftplib](https://docs.python.org/3/library/ftplib.html). There is also a Secure File Transfer Protocol (SFTP) that uses SSH to encrypt the communication. We will focus just on traditional FTP in this guide. For SFTP you can check out the [Paramiko](https://docs.paramiko.org/en/stable/api/sftp.html) package. In this guide, we will look at some basic operations like: - Connect and login to an FTP server - List directories and files - Upload and download files Note these examples are all using Python 3.

Introduction

FTP or File Transfer Protocol is a common way to transfer files.
For FTP, Python has a built in package called ftplib.

There is also a Secure File Transfer Protocol (SFTP) that uses
SSH to encrypt the communication. We will focus just on traditional
FTP in this guide. For SFTP you can check out the
Paramiko package.

In this guide, we will look at some basic operations
like:

  • Connect and login to an FTP server
  • List directories and files
  • Upload and download files

Note these examples are all using Python 3.

Connect to an FTP server

The first thing to learn is how to connect to an FTP server.
We’ll look at how to connect anonymously and

  • Port 21 — Default FTP port

Anonymous connection

This first example shows how to use a with context manager
to login to an FTP server. The connection will automatically
be closed. The code will print out the welcome banner
just to ensure it connected.

# Anonymous FTP login
from ftplib import FTP

with FTP('ftp.example.com') as ftp:
    print(ftp.getwelcome())

Authenticated login

If you want to authenticate, you can simply pass the user and passwd parameters to the FTP() constructor or you can
call connect() and login() yourself. This example
shows how to login using both methods.

from ftplib import FTP

# Connect and login at once
with FTP(host='ftp.example.com', user='me', passwd='secret') as ftp:
    print(ftp.getwelcome())

# Or connect and login as separate steps
ftp = FTP()
ftp.connect('ftp.example.com', 21)
ftp.login('me', 'secret')
print(ftp.getwelcome())
ftp.close()

Connect with SSL/TLS

Use the ftplib.FTP_TLS class instead.
Note, this is not SFTP that uses SSH over port 22, this is
FTP with SSL/TLS over port 21. If your provider offers
this option, always use it over the plaintext FTP.

Then make sure you call ftplib.FTP_TLS.prot_p() which will
setup the secure data connection.

from ftplib import FTP_TLS

# Connect to server using TLS, port 21 default. Is not SFTP over SSH
with FTP_TLS('ftp.example.com', 'user', 'secret') as ftp:
    print(ftp.getwelcome())

Work with directories

Let’s look first at how to do some basic operations
with directories like:

  • printing your current working directory
  • changing directories
  • creating a directory
  • removing a directory

Print current working directory

Once you are connected, you will first want to know
where you are in the directory structure. The pwd()
function on the ftplib.FTP object provides this data.

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    print(ftp.pwd())  # Usually default is /

Create a directory

You can make a directory using ftplib.FTP.mkd() and pass
it the name of the directory. It will return a string
containing the name of the directory created.

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    ftp.mkd('my_dir')

Remove a directory

To remove a directory, just use rmd() on your FTP object.
A directory must be empty to delete it.

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    ftp.rmd('my_dir')

Change current working directory

To switch to a different directory, use ftplib.FTP.cwd().

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    print(ftp.cwd('other_dir'))  # Change to `other_dir/`

List directory contents

The next basic task you will probably want to do is list
the files in a directory. The ftplib.FTP.dir() command
will list all the files in your current directory.

It does not just provide the filename though, it provides
a string that contains the permissions, whether it is a directory,
byte size, modification timestamp, owner, and group information.
It is formatted just like the output from an ls command.
Since the output is a string, you will have to parse out the
information from it manually using split() or regular expressions.

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    # List files
    files = []
    ftp.dir(files.append)  # Takes a callback for each file
    for f in files:
        print(f)

An example file listing might look similar too:

drwxr-xr-x  3 dano   dano  4096 Mar 12 23:15 www-null

Work with files

Now that we have learned how to navigate directories,
it is time to learn how to:

  • upload files
  • download files
  • get the size of a file
  • rename a file
  • delete a file

Upload a file

You may not be able to upload a file on every server,
especially if you are only logged in anonymously.
If you do have the permissions though, this example
will show you how to upload a file.

For text files use storlines() and for binary use
storbinary().

from ftplib import FTP

with FTP('ftp.example.com', 'user', 'pass') as ftp:

    # For text or binary file, always use `rb`
    with open('test.txt', 'rb') as text_file:
        ftp.storlines('STOR test.txt', text_file)
    with open('image.png', 'rb') as image_file:
        ftp.storbinary('STOR image.png', image_file)

Get the size of a file

To check the size of a file on a remote FTP server,
you can simply use the size() function as demonstrated
in the following example.

Depending on whether you want to check a text file
or a binary file, you want to tell the FTP server
what type you want to use. Use sendcmd() and pass
the type with either TYPE I for image/binary data
or TYPE A for ASCII text.

The size() function will return the size
of the file in bytes.

from ftplib import FTP, all_errors

with FTP('ftp.example.com', 'user', 'pass') as ftp:
    try:
        ftp.sendcmd('TYPE I')  # "Image" or binary data
        print(ftp.size('image.png')) # Get size of 'image.png' on server
    except all_errors as error:
        print(f"Error checking image size: {error}")

    try:
        ftp.sendcmd('TYPE A')  # "ASCII" text
        print(ftp.size('test.txt'))
    except all_errors as error:
        print(f"Error checking text file size: {error}")

Rename a file

To rename a file on a remote FTP server, use the rename()
function and pass the original filename and the new filename.

from ftplib import FTP, all_errors

with FTP('ftp.example.com', 'user', 'pass') as ftp:
    try:
        ftp.rename('test.txt', 'my_file.txt')
    except all_errors as error:
        print(f'Error renaming file on server: {error}')

Download a file

To download a file you can use retrlines() or retrbinary() on the FTP object.

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

For the callback, we’ll use write() on the file object so
each chunk is written to the file we have open.

from ftplib import FTP, all_errors

with FTP('ftp.example.com', 'user', 'pass') as ftp:

    # For text files
    with open('local_test.txt', 'w') as local_file:  # Open local file for writing
        # Download `test.txt` from server and write to `local_file`
        # Pass absolute or relative path
        response = ftp.retrlines('RETR test.txt', local_file.write)

        # Check the response code
        # https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes
        if response.startswith('226'):  # Transfer complete
            print('Transfer complete')
        else:
            print('Error transferring. Local file may be incomplete or corrupt.')

    # For binary use `retrbinary()`
    with open('image.png', 'wb') as local_file:
        ftp.retrbinary('RETR image.png', local_file.write)

Delete a file

To delete a remote file, use the delete() function and give it the filename you want to delete. You cannot delete directories with this.
For directories, you must use rmd() as shown in the example earlier.

from ftplib import FTP, all_errors

with FTP('ftp.example.com', 'user', 'pass') as ftp:
    try:
        ftp.delete('test.txt')
    except all_errors as error:
        print(f'Error deleting file: {error}') 

Error checking

So far, none of the examples here include any exception handling.
There are a few exceptions that may be thrown if the server
returns an error or malformed response.

To catch everything, wrap your code with a try statement and catch all FTP exceptions with ftplib.all_errors.

Some of the exceptions to watch for are:

  • ftplib.error_reply — unexpected server reply
  • ftplib.error_temp — temporary error
  • ftplib.error_perm — permanent error
  • ftplib.error_proto — malformed server reply
  • ftplib.all_errors — catches all above errors that a server can return and OSError and EOFError.
from ftplib import FTP

with FTP('ftp.example.com', 'user', 'secret') as ftp:
    try:
        print(ftp.pwd())
    except ftplib.all_errors as e:
        print(f'Error with FTP: {e}')

Conclusion

After reading this guide, you should understand how to
connect to an FTP server with or without TLS and login anonymously or as an authenticated user. You should also understand how to move around directories, create and delete directories, list files, and upload and download files from FTP.

References

  • ftplib
  • Paramiko

Python 3.7

21.13. ftplib — FTP protocol client

Source code: 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.

Here’s a sample session using the ftplib module:

>>> from ftplib import FTP
>>> ftp = FTP('ftp.debian.org')     # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd [email protected]
'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.'
>>> ftp.retrbinary('RETR README', open('README', 'wb').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.

The FTP class supports the with statement, e.g.:

>>> 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
>>>

Changed in version 3.2: Support for the with statement was added.

Changed in version 3.3: source_address parameter was added.

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 Security considerations 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.

New in version 3.2.

Changed in version 3.3: source_address parameter was added.

Here’s a sample session using the FTP_TLS class:

>>> 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 raised when an unexpected reply is received from the server.

exception ftplib.error_temp

Exception raised when an error code signifying a temporary error (response
codes in the range 400–499) is received.

exception ftplib.error_perm

Exception raised when an error code signifying a permanent error (response
codes in the range 500–599) is received.

exception ftplib.error_proto

Exception raised when a reply is received from the server that does not fit
the response specifications of the File Transfer Protocol, i.e. begin with a
digit in the range 1–5.

ftplib.all_errors

The set of all exceptions (as a tuple) that methods of FTP
instances 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 as OSError.

See also

Module netrc
Parser for the .netrc file format. The file .netrc is
typically used by FTP clients to load user authentication information
before prompting the user.

21.13.1. 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 instances have the following methods:

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.

Changed in version 3.3: source_address parameter was added.

FTP.getwelcome()

Return the welcome message sent by the server in reply to the initial
connection. (This message sometimes contains disclaimers or help information
that may be relevant to the user.)

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
'[email protected]'. 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()

Abort a file transfer that is in progress. Using this does not always work, but
it’s worth a try.

FTP.sendcmd(cmd)

Send a simple command string to the server and return the response string.

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.

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)

Enable “passive” mode if val is true, otherwise disable passive mode.
Passive mode is on by default.

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.

Changed in version 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)

Initiate a transfer over the data connection. If the transfer is active, send an
EPRT or PORT command and the transfer command specified by cmd, and
accept the connection. If the server is passive, send an EPSV or PASV
command, connect to it, and start the transfer command. Either way, return the
socket for the connection.

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)

Like transfercmd(), but returns a tuple of the data connection and the
expected size of the data. If the expected size could not be computed, None
will be returned as the expected size. cmd and rest means the same thing as
in transfercmd().

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

List a directory in a standardized format by using MLSD command
(RFC 3659). If path is omitted the current directory is assumed.
facts is a list of strings representing the type of information desired
(e.g. ["type", "size", "perm"]). Return a generator object yielding a
tuple of two elements for every file found in path. First element is the
file name, the second one is a dictionary containing facts about the file
name. Content of this dictionary might be limited by the facts argument
but server is not guaranteed to return all requested facts.

New in version 3.3.

FTP.nlst(argument[, ])

Return a list of file names as returned by the NLST command. 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 NLST command.

Note

If your server supports the command, mlsd() offers a better 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.

Note

If your server supports the command, mlsd() offers a better API.

FTP.rename(fromname, toname)

Rename file fromname on the server to toname.

FTP.delete(filename)

Remove the file named filename from the server. If successful, returns the
text of the response, otherwise raises error_perm on permission errors or
error_reply on other errors.

FTP.cwd(pathname)

Set the current directory on the server.

FTP.mkd(pathname)

Create a new directory on the server.

FTP.pwd()

Return the pathname of the current directory on the server.

FTP.rmd(dirname)

Remove the directory named dirname on the server.

FTP.size(filename)

Request the size of the file named filename on the server. On success, the
size of the file is returned as an integer, otherwise None is returned.
Note that the SIZE command is not standardized, but is supported by many
common server implementations.

FTP.quit()

Send a QUIT command to the server and close the connection. This is the
“polite” way to close a connection, but it may raise an exception if the server
responds with an error to the QUIT command. This implies a call to the
close() method which renders the FTP instance useless for
subsequent calls (see below).

FTP.close()

Close the connection unilaterally. This should not be applied to an already
closed connection such as after a successful call to quit().
After this call the FTP instance should not be used any more (after
a call to close() or quit() you cannot reopen the
connection by issuing another login() method).

21.13.2. 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()

Set up a secure control connection by using TLS or SSL, depending on what
is specified in the ssl_version attribute.

FTP_TLS.ccc()

Revert control channel back to plaintext. This can be useful to take
advantage of firewalls that know how to handle NAT with non-secure FTP
without opening fixed ports.

New in version 3.3.

FTP_TLS.prot_p()

Set up secure data connection.

FTP_TLS.prot_c()

Set up clear text data connection.

From Get docs

Python/docs/3.6/library/ftplib

Jump to:navigation, search

21.13. ftplib — FTP protocol client

Source code: :source:`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.

Here’s a sample session using the ftplib module:

>>> from ftplib import FTP
>>> ftp = FTP('ftp.debian.org')     # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd [email protected]
'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.'
>>> ftp.retrbinary('RETR README', open('README', 'wb').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.

The FTP class supports the with statement, e.g.:

>>> 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
>>>

Changed in version 3.2: Support for the with statement was added.

Changed in version 3.3: source_address parameter was added.

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 Security considerations 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.

New in version 3.2.

Changed in version 3.3: source_address parameter was added.

Here’s a sample session using the FTP_TLS class:

>>> 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 raised when an unexpected reply is received from the server.
exception ftplib.error_temp
Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received.
exception ftplib.error_perm
Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received.
exception ftplib.error_proto
Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, i.e. begin with a digit in the range 1–5.
ftplib.all_errors
The set of all exceptions (as a tuple) that methods of FTP instances 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 as OSError.

See also

Module netrc
Parser for the .netrc file format. The file .netrc is typically used by FTP clients to load user authentication information before prompting the user.

21.13.1. 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 instances have the following methods:

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.

Changed in version 3.3: source_address parameter was added.

FTP.getwelcome()
Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.)
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 '[email protected]'. 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()
Abort a file transfer that is in progress. Using this does not always work, but it’s worth a try.
FTP.sendcmd(cmd)
Send a simple command string to the server and return the response string.
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.
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)
Enable “passive” mode if val is true, otherwise disable passive mode. Passive mode is on by default.
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.

Changed in version 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)

Initiate a transfer over the data connection. If the transfer is active, send an EPRT or PORT command and the transfer command specified by cmd, and accept the connection. If the server is passive, send an EPSV or PASV command, connect to it, and start the transfer command. Either way, return the socket for the connection.

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)
Like transfercmd(), but returns a tuple of the data connection and the expected size of the data. If the expected size could not be computed, None will be returned as the expected size. cmd and rest means the same thing as in transfercmd().
FTP.mlsd(path=, facts=[])

List a directory in a standardized format by using MLSD command (RFC 3659). If path is omitted the current directory is assumed. facts is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary containing facts about the file name. Content of this dictionary might be limited by the facts argument but server is not guaranteed to return all requested facts.

New in version 3.3.

FTP.nlst(argument[, ])

Return a list of file names as returned by the NLST command. 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 NLST command.

Note

If your server supports the command, mlsd() offers a better 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.

Note

If your server supports the command, mlsd() offers a better API.

FTP.rename(fromname, toname)
Rename file fromname on the server to toname.
FTP.delete(filename)
Remove the file named filename from the server. If successful, returns the text of the response, otherwise raises error_perm on permission errors or error_reply on other errors.
FTP.cwd(pathname)
Set the current directory on the server.
FTP.mkd(pathname)
Create a new directory on the server.
FTP.pwd()
Return the pathname of the current directory on the server.
FTP.rmd(dirname)
Remove the directory named dirname on the server.
FTP.size(filename)
Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations.
FTP.quit()
Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below).
FTP.close()
Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method).

21.13.2. 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()

Set up a secure control connection by using TLS or SSL, depending on what is specified in the ssl_version attribute.

FTP_TLS.ccc()

Revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports.

New in version 3.3.

FTP_TLS.prot_p()
Set up secure data connection.
FTP_TLS.prot_c()
Set up clear text data connection.

ftplib-клиент протокола FTP

Source code:Lib/ftplib.py

Этот модуль определяет класс FTP и несколько связанных элементов. Класс FTP реализует клиентскую часть протокола FTP. Вы можете использовать это для написания программ Python, которые выполняют различные автоматизированные задания FTP, такие как зеркалирование других FTP-серверов. Он также используется модулем urllib.request для обработки URL-адресов, использующих FTP. Дополнительные сведения о FTP (протоколе передачи файлов) см. в Internet RFC 959 .

Кодировка по умолчанию — UTF-8 в соответствии с RFC 2640 .

Доступность : не Emscripten, не WASI.

Этот модуль не работает или недоступен на платформах WebAssembly wasm32-emscripten и wasm32-wasi . Дополнительную информацию см. в разделе Платформы WebAssembly .

Вот пример сеанса с использованием модуля ftplib :

>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org')  
>>> ftp.login()                     
'230 Login successful.'
>>> ftp.cwd('debian')               
'250 Directory successfully changed.'
>>> ftp.retrlines('LIST')           
-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.'

Модуль определяет следующие элементы:

class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')

Вернуть новый экземпляр класса FTP . Когда указан host , выполняется вызов метода connect(host) . Когда указан user , дополнительно выполняется login(user, passwd, acct) вызова метода (user, passwd, acct) (где passwd и acct по умолчанию используют пустую строку, если не заданы). Необязательный параметр тайм-аута указывает тайм-аут в секундах для блокирующих операций, таких как попытка подключения (если не указан, будет использоваться глобальная настройка тайм-аута по умолчанию). source_address — это набор из двух кортежей (host, port) к которому сокет будет привязан в качестве адреса источника перед подключением. кодирование Параметр определяет кодировку каталогов и имен файлов.

Класс 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 .

Изменено в версии 3.9: если параметр тайм -аута установлен равным нулю, он вызовет ValueError , чтобы предотвратить создание неблокирующего сокета. Был добавлен параметр кодировки , а значение по умолчанию было изменено с Latin-1 на UTF-8 в соответствии с RFC 2640 .

class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8')

Подкласс FTP , который добавляет к FTP поддержку TLS, как описано в RFC 4217 . Подключитесь, как обычно, к порту 21, неявно защищая управляющее соединение FTP перед аутентификацией. Для защиты подключения к данным пользователь должен явно запросить его, вызвав метод prot_p() . context — это объект ssl.SSLContext , который позволяет объединять параметры конфигурации SSL, сертификаты и закрытые ключи в единую (потенциально долгоживущую) структуру. Ознакомьтесь с рекомендациями по безопасности .

keyfile и certfile являются устаревшей альтернативой context — они могут указывать на закрытый ключ в формате PEM и файлы цепочки сертификатов (соответственно) для соединения SSL.

Новинка в версии 3.2.

Изменено в версии 3.3: добавлен параметр source_address .

Изменено в версии 3.9: если параметр тайм -аута установлен равным нулю, он вызовет ValueError , чтобы предотвратить создание неблокирующего сокета. Был добавлен параметр кодировки , а значение по умолчанию было изменено с 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']
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 .

See also

Modulenetrc

Парсер для файлов формата .netrc . Файл .netrc обычно используется FTP-клиентами для загрузки информации аутентификации пользователя перед запросом пользователя.

FTP Objects

Доступно несколько методов в двух вариантах: один для обработки текстовых файлов, а другой — для двоичных файлов. Они названы в честь используемой команды, за которой следуют lines для текстовой версии или binary для двоичной версии.

FTP экземпляров FTP есть следующие методы:

FTP.set_debuglevel(level)

Установите уровень отладки экземпляра. Это контролирует количество напечатанного отладочного вывода. Значение по умолчанию, 0 , не выводит отладочный вывод. Значение 1 дает умеренный объем отладочной информации, как правило, одну строку на запрос. Значение 2 или выше обеспечивает максимальный объем отладочной информации, регистрируя каждую строку, отправленную и полученную по управляющему соединению.

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

Подключитесь к данному хосту и порту. Номер порта по умолчанию — 21 , как указано в спецификации протокола FTP. Указывать другой номер порта требуется редко. Эта функция должна вызываться только один раз для каждого экземпляра; его вообще не следует вызывать, если хост был указан при создании экземпляра. Все остальные методы можно использовать только после подключения. Необязательный параметр timeout указывает время ожидания в секундах для попытки подключения. Если тайм-аут не пройден, будет использоваться глобальная настройка тайм-аута по умолчанию. source_address — это кортеж из двух элементов (host, port) к которому сокет будет привязан в качестве адреса источника перед подключением.

Вызывает событие аудита ftplib.connect с аргументами self , host , port .

Изменено в версии 3.3: добавлен параметр source_address .

FTP.getwelcome()

Верните приветственное сообщение,отправленное сервером в ответ на первоначальное соединение.(Это сообщение иногда содержит отказ от ответственности или справочную информацию,которая может иметь отношение к пользователю).

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

Войдите в систему как указанный пользователь . Параметры passwd и acct являются необязательными и по умолчанию содержат пустую строку. Если пользователь не указан, по умолчанию используется 'anonymous' . Если пользователь 'anonymous' ,пароль по умолчанию будет 'anonymous@' . Эту функцию следует вызывать только один раз для каждого экземпляра после установления соединения; его вообще не следует вызывать, если хост и пользователь были заданы при создании экземпляра. Большинство команд FTP разрешены только после того, как клиент вошел в систему. Параметр acct предоставляет «учетную информацию»; несколько систем реализуют это.

FTP.abort()

Прервать выполняющуюся передачу файла.Это не всегда срабатывает,но попробовать стоит.

FTP.sendcmd(cmd)

Отправьте простую командную строку на сервер и верните строку ответа.

Вызывает событие аудита ftplib.sendcmd с аргументами self , cmd .

FTP.voidcmd(cmd)

Отправьте простую командную строку на сервер и обработайте ответ. Ничего не возвращать, если получен код ответа, соответствующий успеху (коды в диапазоне 200–299). В противном случае вызовите error_reply .

Вызывает событие аудита ftplib.sendcmd с аргументами self , cmd .

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

Получить файл в двоичном режиме передачи. cmd должна быть соответствующей командой RETR : 'RETR filename' . Функция обратного вызова вызывается для каждого полученного блока данных с одним байтовым аргументом, указывающим блок данных. Необязательный аргумент blockize указывает максимальный размер блока для чтения на низкоуровневом объекте сокета, созданном для фактической передачи (который также будет наибольшим размером блоков данных, переданных в обратный вызов ). Выбрано разумное значение по умолчанию. rest означает то же самое, что и в методе transfercmd() .

FTP.retrlines(cmd, callback=None)

Получить список файлов или каталогов в кодировке, указанной параметром кодировки при инициализации. cmd должна быть соответствующей командой RETR (см. retrbinary() ) или такой командой, как LIST или NLST (обычно это просто строка 'LIST' ). LIST извлекает список файлов и информацию об этих файлах. NLST получает список имен файлов. Функция обратного вызова вызывается для каждой строки со строковым аргументом, содержащим строку с удаленным завершающим CRLF. Обратный вызов по умолчанию выводит строку в sys.stdout .

FTP.set_pasv(val)

Включите «пассивный» режим, если val равно true, в противном случае отключите пассивный режим. Пассивный режим включен по умолчанию.

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

Сохраните файл в двоичном режиме передачи. cmd должна быть соответствующей командой STOR : "STOR filename" . fp — это файловый объект (открытый в двоичном режиме), который считывается до завершения EOF с использованием метода read() в блоках размера блока для предоставления данных для сохранения. Аргумент размера блока по умолчанию равен 8192. Обратный вызов — это необязательный единственный вызываемый параметр, который вызывается для каждого блока данных после его отправки. rest означает то же самое, что и в методе transfercmd() .

Изменено в версии 3.2: добавлен параметр rest .

FTP.storlines(cmd, fp, callback=None)

Сохранить файл в построчном режиме. cmd должна быть подходящей командой STOR (см. storbinary() ). Строки считываются до EOF из файлового объекта fp (открытого в двоичном режиме) с использованием его метода readline() для предоставления данных для сохранения. callback — это необязательный единственный вызываемый параметр, который вызывается в каждой строке после ее отправки.

FTP.transfercmd(cmd, rest=None)

Инициируйте передачу через соединение для передачи данных. Если передача активна, отправьте команду EPRT или PORT и команду передачи, указанную cmd , и подтвердите соединение. Если сервер пассивен, отправьте команду EPSV или PASV , подключитесь к нему и запустите команду передачи. В любом случае верните сокет для подключения.

Если задан необязательный отдых , на сервер отправляется команда REST с передачейотдыха в качестве аргумента. rest обычно представляет собой смещение байтов в запрошенном файле, сообщая серверу о необходимости перезапустить отправку байтов файла с запрошенным смещением, пропуская начальные байты. Однако обратите внимание, что метод transfercmd() преобразует rest в строку с параметром кодирования , указанным при инициализации, но проверка содержимого строки не выполняется. Если сервер не распознает команду REST , будет возбуждено исключение error_reply .Если это произойдет, просто вызовите transfercmd() безостальные аргументы.

FTP.ntransfercmd(cmd, rest=None)

Подобно transfercmd() , но возвращает кортеж подключения к данным и ожидаемый размер данных. Если ожидаемый размер не может быть вычислен, в качестве ожидаемого будет возвращено значение None . cmd и rest означают то же, что и в transfercmd() .

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

Список каталогов в стандартном формате с помощью команды MLSD ( RFC 3659 ). Если путь не указан, предполагается текущий каталог. facts — это список строк, представляющих тип желаемой информации (например ["type", "size", "perm"] ). Возврат объекта-генератора, дающего кортеж из двух элементов для каждого файла, найденного в пути. Первый элемент — это имя файла, второй — словарь, содержащий факты об имени файла. Содержание этого словаря может быть ограничено аргументом фактов , но сервер не гарантирует возврат всех запрошенных фактов.

Новинка в версии 3.3.

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

Вернуть список имен файлов, возвращенный командой NLST . Необязательный аргумент — это каталог, который нужно перечислить (по умолчанию это текущий каталог сервера). Для передачи нестандартных параметров команде NLST можно использовать несколько аргументов .

Note

Если ваш сервер поддерживает команду, mlsd() предлагает лучший API.

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

Создайте список каталогов, возвращенный командой LIST , и распечатайте его на стандартный вывод. Необязательный аргумент — это каталог, который нужно перечислить (по умолчанию это текущий каталог сервера). Для передачи нестандартных параметров команде LIST можно использовать несколько аргументов . Если последний аргумент является функцией, он используется как функция обратного вызова, как и для retrlines() ; по умолчанию распечатывается в sys.stdout . Этот метод возвращает None .

Note

Если ваш сервер поддерживает команду, 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 Класс FTP_TLS наследуется от FTP , определяя следующие дополнительные объекты:

FTP_TLS.ssl_version

Используемая версия SSL (по умолчанию ssl.PROTOCOL_SSLv23 ).

FTP_TLS.auth()

Установите безопасное управляющее соединение с использованием TLS или SSL, в зависимости от того, что указано в ssl_version .

FTP_TLS.ccc()

Переключите канал управления обратно на простой текст.Это может быть полезно,чтобы воспользоваться преимуществами брандмауэров,которые знают,как работать с NAT с небезопасным FTP без открытия фиксированных портов.

Новинка в версии 3.3.

FTP_TLS.prot_p()

Настройте безопасное соединение передачи данных.

FTP_TLS.prot_c()

Настройте соединение для передачи текстовых данных.


Python

3.11

  • дроби-Рациональные числа

    Исходный код:Lib/fractions.py Модуль fractions обеспечивает поддержку арифметики рациональных чисел.

  • Program Frameworks

    Модули,описанные в этой главе,являются каркасами,которые во многом будут диктовать структуру вашей программы.

  • Модули функционального программирования

    Модули,описанные в этой главе,предоставляют функции и классы,которые поддерживают стиль функционального программирования,общие операции callables.

  • Built-in Functions

    Интерпретатор Python имеет ряд встроенных функций и типов,которые всегда доступны.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ftp сервер открывается через браузер как исправить
  • Ftp socket error 10054
  • Ftp error failed to retrieve directory listing
  • Fs error opendir 13 picasso
  • Frosty mod manager ошибка пустое имя пути не допускается

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии