使用python通过FTP下载大文件

Str*_*rae 7 python ftp file-transfer

我试图每天从我的服务器下载备份文件到我的本地存储服务器,但我遇到了一些问题.

我写了这段代码(删除了无用的部分,作为电子邮件功能):

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

day = strftime("%d")
today = strftime("%d-%m-%Y")

link = FTP(ftphost)
link.login(passwd = ftp_pass, user = ftp_user)
link.cwd(file_path)
link.retrbinary('RETR ' + file_name, open('/var/backups/backup-%s.tgz' % today, 'wb').write)
link.delete(file_name) #delete the file from online server
link.close()
mail(user_mail, "Download database %s" % today, "Database sucessfully downloaded: %s" % file_name)
exit()
Run Code Online (Sandbox Code Playgroud)

我用crontab运行它,如:

40    23    *    *    *    python /usr/bin/backup-transfer.py >> /var/log/backup-transfer.log 2>&1
Run Code Online (Sandbox Code Playgroud)

它适用于小文件,但随着备份文件(大约1.7Gb)冻结,下载的文件大约1.2Gb然后永远不会长大(我等了大约一天),日志文件是空的.

任何的想法?

ps:即时通讯使用Python 2.6.5

Str*_*rae 10

对不起,如果我回答我自己的问题,但我找到了解决方案.

我尝试了ftputil没有成功,所以我尝试了很多方式,最后,这工作:

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

downloaded = open('/local/path/to/file.tgz', 'wb')

def debug(txt):
    print txt

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")
[...]
Run Code Online (Sandbox Code Playgroud)

在我的日志文件中,我发现:

01-12-2011 23.30 - Connected to FTP
01-12-2011 23.30 while > try, run retrbinary
02-12-2011 00.31 while > except, something going wrong: timed out
    file lenght is: 1754695793 > 1754695793
02-12-2011 00.31 - Connected to FTP
Done with file, attempt to download m5dsum
Run Code Online (Sandbox Code Playgroud)

可悲的是,我必须重新连接到FTP,即使文件已经完全下载,在我的cas中也不是问题,因为我也必须下载md5sum.

正如您所看到的,我无法检测到超时并重试连接,但是当我超时时,我只是重新连接; 如果有人知道如何重新连接而不创建新的ftplib.FTP实例,请告诉我;)