-1

how can I connect to an FTPS server and download files in it? Currently I am using the following code to retrieve some files in FTPS Server built with Docker.

import ftplib
import os
from dateutil import parser
from datetime import datetime

def connect(host, port, user, password):
    ftp = ftplib.FTP_TLS()
    ftp.debugging = 2
    ftp.connect(host, port)
    ftp.login(user, password)
    return ftp


def retrieveFileList(ftp, ftp_paths, fileType, destinationPath, date):
    total_files = []
    timestamps = []
    for path in ftp_paths:
        currentPath = os.getcwd()
        os.chdir(destinationPath)
        ftp.cwd(path)
        files = ftp.nlst('*'+ fileType)
        for file in files:
            timestamp = ftp.voidcmd("MDTM " + file)[4:].strip()
            time = parser.parse(timestamp)
            parsed_time = time.strftime("%Y-%m")
            timestamps.append(parsed_time)
            if not date > parsed_time:
                total_files.append(file)
                with open(file, 'wb') as f:
                    ftp.retrbinary('RETR ' + file, f.write)
        os.chdir(currentPath)
    max_timestamp = max(timestamps)
    return total_files, max_timestamp

My questions are the following:

  1. Do I have to verify server certificate?
  2. Do I have to create an SSL context and pass it as parameter in FTP_TLS()
  3. Do I need a certificate (client certificate) in order to connect to the server?

I cannot find any complete code example or explanation online, can anyone help me?

leop
  • 41
  • 7

1 Answers1

1

The documentation suggests you must call prot_p to switch to TLS. So your connect() function should look like:

def connect(host, port, user, password):
    ftp = ftplib.FTP_TLS()
    ftp.debugging = 2
    ftp.connect(host, port)
    ftp.prot_p()
    ftp.login(user, password)
    return ftp

The documentation doesn't say SSL context is required. The source code shows the same. That means a default context will be used. You would probably need a custom context if the server certificate is not publicly trusted. If the server is using a self-signed certificate or a certificate signed by an internal CA, you would probably need a custom context.

As for client certificate, that depends on your specific server requirements.

kichik
  • 33,220
  • 7
  • 94
  • 114