python 实现ftp上传下载
* 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验
* 运行示例
[root@vm172-31-16-11 software]# python file.txt 2d6c30dba93eda3f70f662a390d8e49c
1 # -*- coding: utf-8 -*- 2 3 from ftplib import FTP 4 import time 5 import tarfile 6 import os 7 import sys 8 import ftplib 9 import hashlib 10 11 filename = sys.argv[1] 12 localpath = '/data/update/' 13 remotepath = '/server' 14 def ftpconnect(host, username, password): 15 ftp = FTP() 16 # ftp.set_debuglevel(2) 17 ftp.connect(host, 21) 18 ftp.login(username, password) 19 print ftp.welcome 20 return ftp 21 def downloadfile(ftp, filename): 22 if os.path.exists(localpath): 23 pass 24 else: 25 os.makedirs(localpath, 0755) 26 bufsize = 1024 27 ftp.cwd(remotepath) 28 ftp.dir() 29 fp = open(localpath + filename,'wb') 30 ftp.retrbinary('RETR %s' % os.path.basename(filename), fp.write, bufsize) 31 fp.close() 32 33 def getFileMD5(): 34 filepath = localpath + filename 35 if os.path.exists(filepath): 36 f = open(filepath,'rb') 37 md5obj = hashlib.md5() 38 md5obj.update(f.read()) 39 hash = md5obj.hexdigest() 40 f.close() 41 return str(hash).upper() 42 else: 43 print "