Sendcmd() Method Of FTP Class In Python

Overview:

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

Example:

from ftplib import FTP

 

# Connect to the FTP server

ftpInstance = FTP();

ftpInstance.set_pasv(False);

 

ftpInstance.connect(host="speedtest.tele2.net");

resp = ftpInstance.getwelcome();

print(resp);

 

# Send USER

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

print(resp);

 

# Send PASS command

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

print(resp);

 

# Download a file

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

print(resp);

 

# Initiate closing of the FTP connection

resp = ftpInstance.sendcmd("QUIT");

print(resp);

 

Output:

220 (vsFTPd 3.0.3)

331 Please specify the password.

230 Login successful.

226 Transfer complete.

221 Goodbye.

 

 


Copyright 2024 © pythontic.com