python实现从ftp服务器下载文件


Posted in Python onMarch 03, 2020

代码之余,将代码过程重要的一些代码段备份一下,如下的代码内容是关于Python从ftp服务器下载文件的的代码,希望能对小伙伴有用途。

#coding=utf-8
'''
 ftp自动下载、自动上传脚本,可以递归目录操作
'''

from ftplib import FTP
import os,sys,string,datetime,time
import socket

class MYFTP:
 def __init__(self, hostaddr, username, password, remotedir, port=21):
 self.hostaddr = hostaddr
 self.username = username
 self.password = password
 self.remotedir = remotedir
 self.port  = port
 self.ftp  = FTP()
 self.file_list = []
 # self.ftp.set_debuglevel(2)
 def __del__(self):
 self.ftp.close()
 # self.ftp.set_debuglevel(0)
 def login(self):
 ftp = self.ftp
 try: 
 timeout = 300
 socket.setdefaulttimeout(timeout)
 ftp.set_pasv(True)
 print u'开始连接到 %s' %(self.hostaddr)
 ftp.connect(self.hostaddr, self.port)
 print u'成功连接到 %s' %(self.hostaddr)
 print u'开始登录到 %s' %(self.hostaddr)
 ftp.login(self.username, self.password)
 print u'成功登录到 %s' %(self.hostaddr)
 debug_print(ftp.getwelcome())
 except Exception:
 print u'连接或登录失败'
 try:
 ftp.cwd(self.remotedir)
 except(Exception):
 print u'切换目录失败'

 def is_same_size(self, localfile, remotefile):
 try:
 remotefile_size = self.ftp.size(remotefile)
 except:
 remotefile_size = -1
 try:
 localfile_size = os.path.getsize(localfile)
 except:
 localfile_size = -1
 debug_print('localfile_size:%d remotefile_size:%d' %(localfile_size, remotefile_size),)
 if remotefile_size == localfile_size:
 return 1
 else:
 return 0
 def download_file(self, localfile, remotefile):
 if self.is_same_size(localfile, remotefile):
 debug_print(u'%s 文件大小相同,无需下载' %localfile)
 return
 else:
 debug_print(u'>>>>>>>>>>>>下载文件 %s ... ...' %localfile)
 #return
 file_handler = open(localfile, 'wb')
 self.ftp.retrbinary(u'RETR %s'%(remotefile), file_handler.write)
 file_handler.close()

 def download_files(self, localdir='./', remotedir='./'):
 try:
 self.ftp.cwd(remotedir)
 except:
 debug_print(u'目录%s不存在,继续...' %remotedir)
 return
 if not os.path.isdir(localdir):
 os.makedirs(localdir)
 debug_print(u'切换至目录 %s' %self.ftp.pwd())
 self.file_list = []
 self.ftp.dir(self.get_file_list)
 remotenames = self.file_list
 #print(remotenames)
 #return
 for item in remotenames:
 filetype = item[0]
 filename = item[1]
 local = os.path.join(localdir, filename)
 if filetype == 'd':
 self.download_files(local, filename)
 elif filetype == '-':
 self.download_file(local, filename)
 self.ftp.cwd('..')
 debug_print(u'返回上层目录 %s' %self.ftp.pwd())
 def upload_file(self, localfile, remotefile):
 if not os.path.isfile(localfile):
 return
 if self.is_same_size(localfile, remotefile):
 debug_print(u'跳过[相等]: %s' %localfile)
 return
 file_handler = open(localfile, 'rb')
 self.ftp.storbinary('STOR %s' %remotefile, file_handler)
 file_handler.close()
 debug_print(u'已传送: %s' %localfile)
 def upload_files(self, localdir='./', remotedir = './'):
 if not os.path.isdir(localdir):
 return
 localnames = os.listdir(localdir)
 self.ftp.cwd(remotedir)
 for item in localnames:
 src = os.path.join(localdir, item)
 if os.path.isdir(src):
 try:
  self.ftp.mkd(item)
 except:
  debug_print(u'目录已存在 %s' %item)
 self.upload_files(src, item)
 else:
 self.upload_file(src, item)
 self.ftp.cwd('..')

 def get_file_list(self, line):
 ret_arr = []
 file_arr = self.get_filename(line)
 if file_arr[1] not in ['.', '..']:
 self.file_list.append(file_arr)
 
 def get_filename(self, line):
 pos = line.rfind(':')
 while(line[pos] != ' '):
 pos += 1
 while(line[pos] == ' '):
 pos += 1
 file_arr = [line[0], line[pos:]]
 return file_arr
def debug_print(s):
 print s

if __name__ == '__main__':
 timenow = time.localtime()
 datenow = time.strftime('%Y-%m-%d', timenow)
 # 配置如下变量
 hostaddr = '211.15.113.45' # ftp地址
 username = 'UserName' # 用户名
 password = '123456' # 密码
 port = 21 # 端口号 
 rootdir_local = 'E:/mypiv' # 本地目录
 rootdir_remote = '/PIV'   # 远程目录
 
 f = MYFTP(hostaddr, username, password, rootdir_remote, port)
 f.login()
 f.download_files(rootdir_local, rootdir_remote)
 
 timenow = time.localtime()
 datenow = time.strftime('%Y-%m-%d', timenow)
 logstr = u"%s 成功执行了备份n" %datenow
 debug_print(logstr)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用reportlab画图示例(含中文汉字)
Dec 03 Python
Python中你应该知道的一些内置函数
Mar 31 Python
python中将函数赋值给变量时需要注意的一些问题
Aug 18 Python
python里使用正则表达式的组嵌套实例详解
Oct 24 Python
详解Django解决ajax跨域访问问题
Aug 24 Python
Python数据分析:手把手教你用Pandas生成可视化图表的教程
Dec 15 Python
python+opencv实现摄像头调用的方法
Jun 22 Python
利用Python实现Shp格式向GeoJSON的转换方法
Jul 09 Python
浅谈Python 递归算法指归
Aug 22 Python
Django DRF认证组件流程实现原理详解
Aug 17 Python
如何利用Python给自己的头像加一个小国旗(小月饼)
Oct 02 Python
pytest fixtures装饰器的使用和如何控制用例的执行顺序
Jan 28 Python
python实现简单的购物程序代码实例
Mar 03 #Python
python实现跨excel sheet复制代码实例
Mar 03 #Python
python剪切视频与合并视频的实现
Mar 03 #Python
详解Pycharm出现out of memory的终极解决方法
Mar 03 #Python
基于python 等频分箱qcut问题的解决
Mar 03 #Python
python实现快递价格查询系统
Mar 03 #Python
使用python 计算百分位数实现数据分箱代码
Mar 03 #Python
You might like
用php实现的下载css文件中的图片的代码
2010/02/08 PHP
php数组操作之键名比较与差集、交集赋值的方法
2014/11/10 PHP
YII2框架中使用yii.js实现的post请求
2017/04/09 PHP
php pdo连接数据库操作示例
2019/11/18 PHP
JavaScript 创建对象和构造类实现代码
2009/07/30 Javascript
JavaScript实现信用卡校验方法
2015/04/07 Javascript
简介可以自动完成UI的AngularJS工具angular-smarty
2015/06/23 Javascript
jQuery+HTML5美女瀑布流布局实现方法
2015/09/21 Javascript
提升jQuery的性能需要做好七件事
2016/01/11 Javascript
浅谈JavaScript的内置对象和浏览器对象
2016/06/03 Javascript
JavaScript 闭包机制详解及实例代码
2016/10/10 Javascript
微信小程序之小豆瓣图书实例
2016/11/30 Javascript
详解JSON Web Token 入门教程
2018/07/30 Javascript
详解jQuery-each()方法
2019/03/13 jQuery
Element实现表格嵌套、多个表格共用一个表头的方法
2020/05/09 Javascript
javascript实现点击按钮切换轮播图功能
2020/09/23 Javascript
JavaScript实现点击切换验证码及校验
2021/01/10 Javascript
vue form表单post请求结合Servlet实现文件上传功能
2021/01/22 Vue.js
python异步任务队列示例
2014/04/01 Python
python&MongoDB爬取图书馆借阅记录
2016/02/05 Python
Python常见字符串操作函数小结【split()、join()、strip()】
2018/02/02 Python
python制作mysql数据迁移脚本
2019/01/01 Python
浅谈Python 列表字典赋值的陷阱
2019/01/20 Python
python实现烟花小程序
2019/01/30 Python
python3正则模块re的使用方法详解
2020/02/11 Python
Jupyter Notebook远程登录及密码设置操作
2020/04/10 Python
pycharm全局搜索的具体步骤
2020/07/28 Python
python 提高开发效率的5个小技巧
2020/10/19 Python
详解python使用金山词霸的翻译功能(调试工具断点的使用)
2021/01/07 Python
应届生学校辅导员求职信
2013/11/07 职场文书
管理站站长岗位职责
2013/11/27 职场文书
企业统计员岗位职责
2013/12/13 职场文书
代理班主任的自我评价
2014/02/04 职场文书
营销经理工作检讨书
2014/11/03 职场文书
个人年度总结报告
2015/03/09 职场文书
2015年推普周活动方案
2015/05/06 职场文书