0

I am trying to download file from FTP using python 2.7. on Windows XP

I am able to connect FTP but getting following error

[Errno 10054] An existing connection was forcibly closed by the remote host

Below is my code .

import os
from time import strftime
from ftplib import FTP

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders


def ftp_connect(path):
    link = FTP(host = 'myservername', timeout = 5) #Keep low timeout
    link.login(passwd = 'mypassword', user = 'myusername')
    debug("%s - Connected to FTP" % strftime("%d-%m-%Y %H.%M"))
    link.cwd(path)
    return link

def writeline(line):
    file.write(line + "\n")


downloaded = open('myfile.txtx', 'wb')

def debug(txt):
    print txt

path="mydir"
filename="myfilename"

link = ftp_connect(path)
file_size = link.size(filename)

max_attempts = 5 #I dont want death loops.

while file_size != downloaded.tell():
    try:
        debug("%s while > try, run retrbinary\n" % strftime("%d-%m-%Y %H.%M"))
        if downloaded.tell() != 0:
            link.retrbinary('RETR ' + filename, downloaded.write, downloaded.tell())
        else:
            link.retrbinary('RETR ' + filename, downloaded.write)
    except Exception as myerror:
        if max_attempts != 0:
            debug("%s while > except, something going wrong: %s\n \tfile lenght is: %i > %i\n" %
                (strftime("%d-%m-%Y %H.%M"), myerror, file_size, downloaded.tell())
            )
            link = ftp_connect(path)
            max_attempts -= 1
        else:
            break
debug("Done with file, attempt to download m5dsum")

I tested separately to log in FTP and was successful. But while executing any command like retrbinary or retrlist getting above error

Thanks in advance

1 Answers1

2

Because FTPS require diff implementation

Using below line of code resolve my problem

ftps = FTP_TLS(server)
ftps.debug(3)
ftps.connect(host=server,port=portno,timeout=60)
ftps.auth()
ftps.login(username, password )
ftps.prot_p()

First connect to ftps server and then login with auth() and prot_p()