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()
相关文章推荐
- python 文件操作
- python学习 第三篇 文件操作
- Python多线程学习
- python 画折线图
- 关于利用Python的pip.exe文件将.whl文件解压为py2exe
- python
- python字符串的操作
- python按行读取文件,如何去掉换行符"\n"
- Python学习笔记之IF
- 【python】lxml查找属性为指定值的节点
- Windows下Python第三方库lxml安装过程中遇到的问题
- 树莓派 让vim支持python
- 在Xcode7中搭建Python开发环境
- Python学习笔记--2016.07.27
- Python自定义函数基础:获取函数单返回值和多返回值
- Python自定义包引入
- Should we always favor xrange() over range()
- 深入理解Python装饰器
- Python之操作RabbitMQ
- Python自动化测试 ConfigParser模块读写配置文件