'Connect to Explicit FTPS (FTPES) with Python (error) [duplicate]

I'm uploading a file ftp and keep getting a "ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2756)" error.

    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:
            session = self.sock.session
            if isinstance(self.sock, ssl.SSLSocket):
                    session = self.sock.session
            conn = self.context.wrap_socket(conn,
                                            server_hostname=self.host,
                                            session=session)  # this is the fix
        return conn, size
tp = MyFTP_TLS()
ftp.ssl_version = ssl.PROTOCOL_TLSv1_2
ftp.connect(server, 21)
ftp.set_pasv(True)
ftp.auth()
ftp.prot_p()
ftp.login(user, passwd)
print("Success connection")
ftp.set_debuglevel(2)
ftp.encoding = "utf-8"
#ftp.getwelcome()
with open(dest_filename,"rb") as file:
    try:
        ftp.storbinary(f"STOR {dest_filename}", file)
    except:
        ftp.quit()
        os.remove(dest_filename)
ftp.quit()
os.remove(dest_filename)

Why is this throwing an error? Ideas?



Solution 1:[1]

This is the code I ended up using. It extends the ftp python class. Basically, do a ftp = MyFTP_TLS() and then do all the calls you want, like ftp.login(user,passwd) etc like normal.

`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)  # reuses TLS session            
        conn.__class__ = ReusedSslSocket  # we should not close reused ssl socket when file transfers finish
    return conn, size`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Dannewitz