Sendcmd() Method Of FTP Class In Python


  • The method sendcmd() of the FTP class sends an FTP command albeit a simple one like USER, PASS, QUIT and not the ones like RETR.
  • The interaction of an FTP client with an FTP server is through two connections
    • A control connection – To send a sequence of commands and get the response. The associated port at the server side is 21 and the port at the client side is a port with number greater than 1024.
    • A Data connection – To transfer data from the FTP server to the FTP client. The associated port at the server side is 20 and the port at the client side is a port with number greater than 1024 as specified by the PORT command. The server connects to this open port at the client side and performs the data transfer. This scheme changes when the Data Transfer is in passive mode instead of active mode.
  • The Python example below uses the method sendcmd() and sends the commands USER and PASS to log into the FTP server.
  • The example uses the method retrbinary() method in active mode, which in turn sends the PORT command and creates a socket for accepting the incoming connection from the FTP server.


from ftplib import FTP


# Connect to the FTP server

ftpInstance = FTP();




resp = ftpInstance.getwelcome();



# Send USER

resp = ftpInstance.sendcmd("USER anonymous");



# Send PASS command

resp = ftpInstance.sendcmd("PASS anonymous@");



# Download a file

resp = ftpInstance.retrbinary("RETR", open('', 'wb').write)



# Initiate closing of the FTP connection

resp = ftpInstance.sendcmd("QUIT");




220 (vsFTPd 3.0.3)

331 Please specify the password.

230 Login successful.

226 Transfer complete.

221 Goodbye.



Copyright 2024 ©