您的位置:首页 > 编程语言 > Python开发

python 实现远端ftp文件上传下载

2016-07-27 12:16 841 查看

python 实现ftp上传下载

* 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验

* 运行示例

[root@vm172-31-16-11 software]# python file.txt 2d6c30dba93eda3f70f662a390d8e49c

# -*- coding: utf-8 -*-

from ftplib import FTP
import time
import tarfile
import os
import sys
import ftplib
import hashlib

filename = sys.argv[1]
localpath = '/data/update/'
remotepath = '/server'
def ftpconnect(host, username, password):
ftp = FTP()
#    ftp.set_debuglevel(2)
ftp.connect(host, 21)
ftp.login(username, password)
print ftp.welcome
return ftp
def downloadfile(ftp, filename):
if  os.path.exists(localpath):
pass
else:
os.makedirs(localpath, 0755)
bufsize = 1024
ftp.cwd(remotepath)
ftp.dir()
fp = open(localpath + filename,'wb')
ftp.retrbinary('RETR %s' % os.path.basename(filename), fp.write, bufsize)
fp.close()

def getFileMD5():
filepath = localpath + filename
if os.path.exists(filepath):
f = open(filepath,'rb')
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
f.close()
return str(hash).upper()
else:
print "\033[1;31;40mERROR:Get the %s MD5 failed\033[0m" % filepath
return None

def file_exists():
filemd5 = getFileMD5()
downloadftpfile = localpath + filename
if os.path.exists(downloadftpfile) and filemd5 == sys.argv[2]:
print "\033[1;32;40m====================ftp down ok and md5 value is ok======================\033[0m"
elif os.path.exists(downloadftpfile) and filemd5 != sys.argv[2]:
print "\033[1;31;40m====================ftp down ok and md5 value is bad======================\033[0m"
else:
print "\033[1;31;40mERROR:The %s is not exists\033[0m" % downloadftpfile

def uploalfile(ftp, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR ' + remotepath, fp, bufsize)
#    ftp.set_debuglevel(0)
ftp.close()

def download():
try:
ftp = ftpconnect("x.x.x.x", "x.x", "x.x")
downloadfile(ftp, filename)
ftp.quit()
file_exists()
except ftplib.error_perm:
os.chdir(localpath)
os.remove(filename)
file_exists()
if __name__ == "__main__":
download()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: