2

So, I'm struggling trying to upload a file to a remote ftps server that requires session reuse.

I must specify that even if I can connect to the server without problems via Filezilla, I get the error "unknown server certificate".

This is my script:

import ftplib
import ssl

USER = "username"
PASS = "password"
SERVER = "1.2.3.4"
PORT = 21
BINARY_STORE = True

filepath = '/path/to/myfile.txt'
filename = 'myfile.txt'

content = open(filepath, 'rb')
ftp = ftplib.FTP_TLS()
ftp.set_debuglevel(2)
print (ftp.connect(SERVER, PORT))
print (ftp.login(USER, PASS))
print (ftp.prot_p())
print (ftp.set_pasv(True))

print (ftp.cwd("testfolder"))
print (ftp.storbinary('STOR %s' % filename, content))
ftp.quit()

But I get this message: 450 TLS session of data connection has not resumed or the session does not match the control connection

The file is created on server but it's empty (0 bytes size) I've read dozen posts and I clearly understood that I must implement session reuse on client side too - which is supported from Python 3.6 - but simply... I don't know how to do this, since I can't find any working example.

Someone suggested to extend FTP_TLS class:

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
ftp = MyFTP_TLS()
...

But now the server response is: 'SSLSocket' object has no attribute 'session'

So I'm stuck. What am I missing?

Ministry
  • 131
  • 4
  • 9
  • 1
    OK! My fault! A silly fault indeed... The default Python3 running version on my system was 5.3.5, so using Python3.6 - and extenting FTP_TLS library as in my example) works like a charm! – Ministry Jan 17 '18 at 11:16
  • I had the same issue using python 3.7.1. When I extended the FTP_TLS library as described, I got an exception, but surprisingly the file was uploaded successfully. – Marcos Aug 23 '19 at 00:04
  • Solution also worked for me in Python 3.7. Code run without hitting any exception. – GuillemB Jan 07 '20 at 10:48

1 Answers1

0

Is this working for you?

from ftplib import FTP_TLS

USER = "username"
PASS = "password"
SERVER = "1.2.3.4"
PORT = 21 

ftps = FTP_TLS(SERVER)
ftps.login(USER, PASS)         
ftps.prot_p()         
ftps.set_pasv(True)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Yes, I forgot to specify that I connect correctly. The error message is raised when I try to transfer the file: ftp.storbinary('STOR %s' % filename, content) – Ministry Jan 15 '18 at 14:07