I had some trouble with the ftplib
module in Python 3, after some debugging, I found the mistake: the getline()
method of the FTP
class returns b'somestring'
(but as a string, not bytes) instead of somestring
. I can solve this with .decode("utf-8")
, replacing the first line in the function
line = self.file.readline(self.maxline + 1)
with
line = self.file.readline(self.maxline + 1).decode("utf-8")
solves the error. But now, I want not to edit the file ftplib.py
manually, instead I want to override it in my code. But while I'm using the FTP_TLS
class, which inherits from FTP
, I can't figure it out, how to do...
class FTP:
def getline(self):
line = self.file.readline(self.maxline + 1).decode("utf-8")
...
at the beginning in my code does not work, because FTP_TLS
doesn't recognize the changes I made to FTP
.
Sample:
import ftplib
import socket
import ssl
class FTP(ftplib.FTP):
def getline(self):
line = self.file.readline(self.maxline + 1).decode("utf-8")
if len(line) > self.maxline:
raise ftplib.Error("got more than %d bytes" % self.maxline)
if self.debugging > 1:
print('*get*', self.sanitize(line))
if not line:
raise EOFError
if line[-2:] == ftplib.CRLF:
line = line[:-2]
elif line[-1:] in ftplib.CRLF:
line = line[:-1]
return line
class FTPS(ftplib.FTP_TLS):
def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, timeout=60):
ftplib.FTP_TLS.__init__(self, host=host, user=user, passwd=passwd, acct=acct, keyfile=keyfile,
certfile=certfile, timeout=timeout)
def connect(self, host='', port=0, timeout=-999, source_address=None):
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ssl_version=ssl.PROTOCOL_TLSv1_2)
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
except Exception as e:
print(e)
return self.welcome
if __name__ == "__main__":
ftps = FTPS()
ftps.connect("host", 990) # Returns b'welcomemessage'
ftps.login("user", "pwd")
ftps.prot_p()
ftps.close()