Transfercmd() Method Of Class FTP In Python

Method Name:


Method Signature:

transfercmd(cmd, rest=None)



cmd – An FTP command for data transfer. E.g., RETR <filename>

rest – A string containing information on where to resume the data transfer.

Return Value:

A socket for transferring data.

Overview of Data Transfer in FTP:

  • Communicating with an FTP server and transferring files between the FTP client and the server involves two connections:
    • A control connection
    • A data connection
  • While a control connection is used for sending commands like USER, PASS, CWD, PWD the data connection is used for transferring files between the FTP client and the FTP server.
  • A data connection can be in any of the two modes:
    • Active Mode
    • Passive Mode
  • In active mode, the FTP client creates a socket and accepts the connection request from the server and the file transfer happens.
  • In passive mode, the FTP server creates a socket and the client connects to it, which is accepted by the server, and the file transfer happens.

How transfercmd() implements the File Transfer over Data Connection:

  • When an ftplib.FTP instance is created, by default the passive mode is on. Through set_pasv() method it can be switched off, which enables the active mode.
  • If the passive mode is enabled on the FTP instance, the transfercmd() method internally sends the FTP command PASV or EPASV and establishes a connection with the server. Note that the socket is created at the server side upon receiving PASV or EPASV and subsequent connection request from the client (i.e., transfercmd() ) is fulfilled by the server. Then the data transfer command is sent from the client to the server on this connection.
  • If the active mode is enabled on the FTP instance, the transfercmd() method internally creates a socket at the client side on a specific port.This port number is sent using the FTP command PORT or EPORT over the control connection followed by the command for data transfer. Subsequently, the FTP client (i.e., transfercmd()) will accept the data connection from the FTP server for data transfer.

Example – Data transfer using the trasnfercmd() function:

# Example Python Program to download a file from an FTP server

# in active mode

from ftplib import FTP


# Create an FTP instance and connect to the FTP server

ftp = FTP(host="")


# Enable active mode



# Login to the FTP server

ftpReply = ftp.login();



# Initiate a file download from server to client in active mode

downloadCommand = "RETR";


# Tell the server that forth coming file transfer is in binary mode

ftpReply = ftp.sendcmd('TYPE I');



with open('', 'wb') as fd:

    with ftp.transfercmd(downloadCommand) as dataConnection:

        while 1:

            data = dataConnection.recv(8192);

            if not data:






230 Login successful.

200 Switching to Binary mode.

226 Transfer complete.

Copyright 2024 ©