在实际工作碰到一个需求,每天需要在大量的服务器上下载更新文件,并且文件都是几个G的大文件,由于服务器数量比较多,且分布在大江南北的联通电信,如果电信的服务器去下载联通源的文件,会很慢,反之亦然,最好能有一个脚本,自动判断到电信的服务器下载服务器快,还是到联通的下载服务器快。
思路是这样的,在电信联通的下载服务器分别放置一个20M大小的测试文件,正式下载之前,分别测试下2个文件的下载所用时间,然后决定使用哪个下载源。
代码如下:
#/usr/bin/env python # big file download mod import os import sys import string import commands import time def getfile(filename,url): a=filename b=url dlcmd="wget "+b+a+" -O /data/"+a+" -c " dlcmdmd5="wget "+b+a+".md5 -O /data/"+a+".md5 -c " os.popen(dlcmd) os.popen(dlcmdmd5) print "**********************************************" return 0 #end def urlTest(url): urlTestCmd="wget -c "+url+"ratetest -O /data/ratetest" rmTestFile="rm -f /data/ratetest*" a=time.time() os.popen(urlTestCmd) os.popen(rmTestFile) b=time.time() c=b-a return c #end def geturl(url1,url2): c1=urlTest(url1) c2=urlTest(url2) if ( c2 < c1): return url2 else: return url1 #end def checkFile(filename,url1,url2): a=filename checkmd5="md5sum -c /data/"+a+".md5" if os.path.isfile("/data/"+a): colpt.ptgreen("vm p_w_picpaths "+a+" exists ok!") return 0 else: print a+" not exists ,Will download " filegeturl=geturl(url1,url2) b=getfile(a,filegeturl) if (b != 0): print "Download errors Please check !" return 11 j=1 statusCheckMd5, outputCheckMd5 = commands.getstatusoutput(checkmd5) print str(statusCheckMd5)+" md5 status is!" print "outputCheckMd5 is "+outputCheckMd5 if (string.find(outputCheckMd5,"OK")>0): statusCheckMd5=0 else: statusCheckMd5=1 while (statusCheckMd5 != 0): os.system("rm /data/"+a+" -f") os.system("rm /data/"+a+"md5 -f") getTemp(a) statusCheckMd5, outputCheckMd5 = commands.getstatusoutput(checkmd5) j=j+1 print str(statusCheckMd5)+" md5 status is!" if (j > 6): print "p_w_picpaths sync filed" return 12 print "file downlaod ok!" return 0 #end
将以上代码作为模块使用,直接调用模块参数就可以:
url1=ftp://2.2.2.2/ #电信区下载服务器 url1=ftp://1.1.1.1/ #联通区下载服务器 filename="bigfile" #需要下载的大文件 bigfileDownload.checkFile(filename,url1,url2)