ftplib — FTP protocol client¶
Source code:Lib/ftplib.py
This module defines the classFTP and a few related items. TheFTP class implements the client side of the FTP protocol. You can usethis to write Python programs that perform a variety of automated FTP jobs, suchas mirroring other FTP servers. It is also used by the moduleurllib.request to handle URLs that use FTP. For more information on FTP(File Transfer Protocol), see internetRFC 959.
The default encoding is UTF-8, followingRFC 2640.
Availability: not WASI.
This module does not work or is not available on WebAssembly. SeeWebAssembly platforms for more information.
Here’s a sample session using theftplib module:
>>>fromftplibimportFTP>>>ftp=FTP('ftp.us.debian.org')# connect to host, default port>>>ftp.login()# user anonymous, passwd anonymous@'230 Login successful.'>>>ftp.cwd('debian')# change into "debian" directory'250 Directory successfully changed.'>>>ftp.retrlines('LIST')# list directory contents-rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README...drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pooldrwxr-sr-x 4 1176 1176 4096 Nov 17 2008 projectdrwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools'226 Directory send OK.'>>>withopen('README','wb')asfp:>>>ftp.retrbinary('RETR README',fp.write)'226 Transfer complete.'>>>ftp.quit()'221 Goodbye.'
Reference¶
FTP objects¶
- classftplib.FTP(host='',user='',passwd='',acct='',timeout=None,source_address=None,*,encoding='utf-8')¶
Return a new instance of the
FTPclass.- Parameters:
host (str) – The hostname to connect to.If given,
connect(host)is implicitly called by the constructor.user (str) – The username to log in with (default:
'anonymous').If given,login(host,passwd,acct)is implicitly calledby the constructor.passwd (str) – The password to use when logging in.If not given, and ifpasswd is the empty string or
"-",a password will be automatically generated.acct (str) – Account information to be used for the
ACCTFTP command.Few systems implement this.SeeRFC-959for more details.timeout (float |None) – A timeout in seconds for blocking operations like
connect()(default: the global default timeout setting).source_address (tuple |None) – A 2-tuple
(host,port)for the socket to bind to as itssource address before connecting.encoding (str) – The encoding for directories and filenames (default:
'utf-8').
The
FTPclass supports thewithstatement, e.g.:>>>fromftplibimportFTP>>>withFTP("ftp1.at.proftpd.org")asftp:...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 CentOSdr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora>>>
Changed in version 3.2:Support for the
withstatement was added.Changed in version 3.3:source_address parameter was added.
Changed in version 3.9:If thetimeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socket.Theencoding parameter was added, and the default was changed fromLatin-1 to UTF-8 to followRFC 2640.Several
FTPmethods are available in two flavors:one for handling text files and another for binary files.The methods are named for the command which is used followed bylinesfor the text version orbinaryfor the binary version.FTPinstances have the following methods:- set_debuglevel(level)¶
Set the instance’s debugging level as an
int.This controls the amount of debugging output printed.The debug levels are:0(default): No debug output.1: Produce a moderate amount of debug output,generally a single line per request.2or higher: Produce the maximum amount of debugging output,logging each line sent and received on the control connection.
- connect(host='',port=0,timeout=None,source_address=None)¶
Connect to the given host and port.This function should be called only once for each instance;it should not be called if ahost argument was givenwhen the
FTPinstance was created.All otherFTPmethods can only be calledafter a connection has successfully been made.- Parameters:
host (str) – The host to connect to.
port (int) – The TCP port to connect to (default:
21,as specified by the FTP protocol specification).It is rarely needed to specify a different port number.timeout (float |None) – A timeout in seconds for the connection attempt(default: the global default timeout setting).
source_address (tuple |None) – A 2-tuple
(host,port)for the socket to bind to as itssource address before connecting.
Raises anauditing event
ftplib.connectwith argumentsself,host,port.Changed in version 3.3:source_address parameter was added.
- getwelcome()¶
Return the welcome message sent by the server in reply to the initialconnection. (This message sometimes contains disclaimers or help informationthat may be relevant to the user.)
- login(user='anonymous',passwd='',acct='')¶
Log on to the connected FTP server.This function should be called only once for each instance,after a connection has been established;it should not be called if thehost anduser arguments were givenwhen the
FTPinstance was created.Most FTP commands are only allowed after the client has logged in.- Parameters:
user (str) – The username to log in with (default:
'anonymous').passwd (str) – The password to use when logging in.If not given, and ifpasswd is the empty string or
"-",a password will be automatically generated.acct (str) – Account information to be used for the
ACCTFTP command.Few systems implement this.SeeRFC-959for more details.
- abort()¶
Abort a file transfer that is in progress. Using this does not always work, butit’s worth a try.
- sendcmd(cmd)¶
Send a simple command string to the server and return the response string.
Raises anauditing event
ftplib.sendcmdwith argumentsself,cmd.
- voidcmd(cmd)¶
Send a simple command string to the server and handle the response. Returnthe response string if the response code corresponds to success (codes inthe range 200–299). Raise
error_replyotherwise.Raises anauditing event
ftplib.sendcmdwith argumentsself,cmd.
- retrbinary(cmd,callback,blocksize=8192,rest=None)¶
Retrieve a file in binary transfer mode.
- Parameters:
cmd (str) – An appropriate
RETRcommand:"RETRfilename".callback (callable) – A single parameter callable that is calledfor each block of data received,with its single argument being the data as
bytes.blocksize (int) – The maximum chunk size to read on the low-level
socketobject created to do the actual transfer.This also corresponds to the largest size of datathat will be passed tocallback.Defaults to8192.rest (int) – A
RESTcommand to be sent to the server.See the documentation for therest parameter of thetransfercmd()method.
- retrlines(cmd,callback=None)¶
Retrieve a file or directory listing in the encoding specified by theencoding parameter at initialization.cmd should be an appropriate
RETRcommand (seeretrbinary()) ora command such asLISTorNLST(usually just the string'LIST').LISTretrieves a list of files and information about those files.NLSTretrieves a list of file names.Thecallback function is called for each line with a string argumentcontaining the line with the trailing CRLF stripped. The defaultcallbackprints the line tosys.stdout.
- set_pasv(val)¶
Enable “passive” mode ifval is true, otherwise disable passive mode.Passive mode is on by default.
- storbinary(cmd,fp,blocksize=8192,callback=None,rest=None)¶
Store a file in binary transfer mode.
- Parameters:
cmd (str) – An appropriate
STORcommand:"STORfilename".fp (file object) – A file object (opened in binary mode) which is read until EOF,using its
read()method in blocks of sizeblocksizeto provide the data to be stored.blocksize (int) – The read block size.Defaults to
8192.callback (callable) – A single parameter callable that is calledfor each block of data sent,with its single argument being the data as
bytes.rest (int) – A
RESTcommand to be sent to the server.See the documentation for therest parameter of thetransfercmd()method.
Changed in version 3.2:Therest parameter was added.
- storlines(cmd,fp,callback=None)¶
Store a file in line mode.cmd should be an appropriate
STORcommand (seestorbinary()). Lines are read until EOF from thefile objectfp (opened in binary mode) using itsreadline()method to provide the data to be stored.callback is an optional singleparameter callable that is called on each line after it is sent.
- transfercmd(cmd,rest=None)¶
Initiate a transfer over the data connection. If the transfer is active, send an
EPRTorPORTcommand and the transfer command specified bycmd, andaccept the connection. If the server is passive, send anEPSVorPASVcommand, connect to it, and start the transfer command. Either way, return thesocket for the connection.If optionalrest is given, a
RESTcommand is sent to the server, passingrest 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 thetransfercmd()method convertsrest to a string with theencoding parameter specifiedat initialization, but no check is performed on the string’s contents. If theserver does not recognize theRESTcommand, anerror_replyexceptionwill be raised. If this happens, simply calltransfercmd()without arest argument.
- ntransfercmd(cmd,rest=None)¶
Like
transfercmd(), but returns a tuple of the data connection and theexpected size of the data. If the expected size could not be computed,Nonewill be returned as the expected size.cmd andrest means the same thing asintransfercmd().
- mlsd(path='',facts=[])¶
List a directory in a standardized format by using
MLSDcommand(RFC 3659). Ifpath 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 atuple of two elements for every file found in path. First element is thefile name, the second one is a dictionary containing facts about the filename. Content of this dictionary might be limited by thefacts argumentbut server is not guaranteed to return all requested facts.Added in version 3.3.
- nlst(argument[,...])¶
Return a list of file names as returned by the
NLSTcommand. Theoptionalargument is a directory to list (default is the current serverdirectory). Multiple arguments can be used to pass non-standard options totheNLSTcommand.Note
If your server supports the command,
mlsd()offers a better API.
- dir(argument[,...])¶
Produce a directory listing as returned by the
LISTcommand, printing it tostandard output. The optionalargument is a directory to list (default is thecurrent server directory). Multiple arguments can be used to pass non-standardoptions to theLISTcommand. If the last argument is a function, it is usedas acallback function as forretrlines(); the default prints tosys.stdout. This method returnsNone.Note
If your server supports the command,
mlsd()offers a better API.
- rename(fromname,toname)¶
Rename filefromname on the server totoname.
- delete(filename)¶
Remove the file namedfilename from the server. If successful, returns thetext of the response, otherwise raises
error_permon permission errors orerror_replyon other errors.
- cwd(pathname)¶
Set the current directory on the server.
- mkd(pathname)¶
Create a new directory on the server.
- pwd()¶
Return the pathname of the current directory on the server.
- rmd(dirname)¶
Remove the directory nameddirname on the server.
- size(filename)¶
Request the size of the file namedfilename on the server. On success, thesize of the file is returned as an integer, otherwise
Noneis returned.Note that theSIZEcommand is not standardized, but is supported by manycommon server implementations.
- quit()¶
Send a
QUITcommand to the server and close the connection. This is the“polite” way to close a connection, but it may raise an exception if the serverresponds with an error to theQUITcommand. This implies a call to theclose()method which renders theFTPinstance useless forsubsequent calls (see below).
- close()¶
Close the connection unilaterally. This should not be applied to an alreadyclosed connection such as after a successful call to
quit().After this call theFTPinstance should not be used any more (aftera call toclose()orquit()you cannot reopen theconnection by issuing anotherlogin()method).
FTP_TLS objects¶
- classftplib.FTP_TLS(host='',user='',passwd='',acct='',*,context=None,timeout=None,source_address=None,encoding='utf-8')¶
An
FTPsubclass which adds TLS support to FTP as described inRFC 4217.Connect to port 21 implicitly securing the FTP control connectionbefore authenticating.Note
The user must explicitly secure the data connectionby calling the
prot_p()method.- Parameters:
host (str) – The hostname to connect to.If given,
connect(host)is implicitly called by the constructor.user (str) – The username to log in with (default:
'anonymous').If given,login(host,passwd,acct)is implicitly calledby the constructor.passwd (str) – The password to use when logging in.If not given, and ifpasswd is the empty string or
"-",a password will be automatically generated.acct (str) – Account information to be used for the
ACCTFTP command.Few systems implement this.SeeRFC-959for more details.context (
ssl.SSLContext) – An SSL context object which allows bundling SSL configuration options,certificates and private keys into a single, potentially long-lived,structure.Please readSecurity considerations for best practices.timeout (float |None) – A timeout in seconds for blocking operations like
connect()(default: the global default timeout setting).source_address (tuple |None) – A 2-tuple
(host,port)for the socket to bind to as itssource address before connecting.encoding (str) – The encoding for directories and filenames (default:
'utf-8').
Added in version 3.2.
Changed in version 3.3:Added thesource_address parameter.
Changed in version 3.4:The class now supports hostname check with
ssl.SSLContext.check_hostnameandServer Name Indication (seessl.HAS_SNI).Changed in version 3.9:If thetimeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socket.Theencoding parameter was added, and the default was changed fromLatin-1 to UTF-8 to followRFC 2640.Changed in version 3.12:The deprecatedkeyfile andcertfile parameters have been removed.
Here’s a sample session using the
FTP_TLSclass:>>>ftps=FTP_TLS('ftp.pureftpd.org')>>>ftps.login()'230 Anonymous user logged in'>>>ftps.prot_p()'200 Data protection level set to "private"'>>>ftps.nlst()['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']
FTP_TLSclass inherits fromFTP,defining these additional methods and attributes:- ssl_version¶
The SSL version to use (defaults to
ssl.PROTOCOL_SSLv23).
- auth()¶
Set up a secure control connection by using TLS or SSL, depending on whatis specified in the
ssl_versionattribute.Changed in version 3.4:The method now supports hostname check with
ssl.SSLContext.check_hostnameandServer Name Indication (seessl.HAS_SNI).
- ccc()¶
Revert control channel back to plaintext. This can be useful to takeadvantage of firewalls that know how to handle NAT with non-secure FTPwithout opening fixed ports.
Added in version 3.3.
- prot_p()¶
Set up secure data connection.
- prot_c()¶
Set up clear text data connection.
Module variables¶
- exceptionftplib.error_reply¶
Exception raised when an unexpected reply is received from the server.
- exceptionftplib.error_temp¶
Exception raised when an error code signifying a temporary error (responsecodes in the range 400–499) is received.
- exceptionftplib.error_perm¶
Exception raised when an error code signifying a permanent error (responsecodes in the range 500–599) is received.
- exceptionftplib.error_proto¶
Exception raised when a reply is received from the server that does not fitthe response specifications of the File Transfer Protocol, i.e. begin with adigit in the range 1–5.
- ftplib.all_errors¶
The set of all exceptions (as a tuple) that methods of
FTPinstances may raise as a result of problems with the FTP connection (asopposed to programming errors made by the caller). This set includes thefour exceptions listed above as well asOSErrorandEOFError.
See also
- Module
netrc Parser for the
.netrcfile format. The file.netrcistypically used by FTP clients to load user authentication informationbefore prompting the user.