FTPS with Python ftplib – Session reuse required

It can be now easily fixed for Python 3.6+ by this class (descendant of FTP_TLS):

class MyFTP_TLS(ftplib.FTP_TLS):
    """Explicit FTPS, with shared TLS session"""
    def ntransfercmd(self, cmd, rest=None):
        conn, size = ftplib.FTP.ntransfercmd(self, cmd, rest)
        if self._prot_p:
            conn = self.context.wrap_socket(conn,
                                            server_hostname=self.host,
                                            session=self.sock.session)  # this is the fix
        return conn, size

It takes the TLS session information from the initial “control” FTP connection and reuses it also for every second “data” connection that is frequently created and closed for every new data transfer of a file body or a directory list. The reuse is advantageous for the server because it does not require a repeated TLS handshake many times. That is exactly what you did see in the message session reuse required.

Leave a Comment