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 相关文章推荐
详解Django中的form库的使用
Jul 18 Python
简述:我为什么选择Python而不是Matlab和R语言
Nov 14 Python
对Python中Iterator和Iterable的区别详解
Oct 18 Python
理想高通滤波实现Python opencv示例
Jan 30 Python
Python中*args和**kwargs的区别详解
Sep 17 Python
简单了解python中的与或非运算
Sep 18 Python
python中的Elasticsearch操作汇总
Oct 30 Python
浅谈Python 函数式编程
Jun 20 Python
Python 如何创建一个简单的REST接口
Jul 30 Python
python实现马丁策略的实例详解
Jan 15 Python
基于flask实现五子棋小游戏
May 25 Python
Python可视化神器pyecharts绘制地理图表
Jul 07 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中使用curl_init函数的说明
2010/11/02 PHP
如何使用Gitblog和Markdown建自己的博客
2015/07/31 PHP
PHP实现图的邻接矩阵表示及几种简单遍历算法分析
2017/11/24 PHP
PHP count_chars()函数讲解
2019/02/14 PHP
javascript中注册和移除事件的4种方式
2013/03/20 Javascript
js调试系列 断点与动态调试[基础篇]
2014/06/18 Javascript
AngularJS实现表单验证
2015/01/28 Javascript
Angular设置title信息解决SEO方面存在问题
2016/08/19 Javascript
jQuery包裹节点用法完整示例
2016/09/13 Javascript
浅谈JavaScript的自动垃圾收集机制
2016/12/15 Javascript
JavaScript设计模式之构造函数模式实例教程
2018/07/02 Javascript
vue项目使用微信公众号支付总结及遇到的坑
2018/10/23 Javascript
小程序日历控件使用方法详解
2018/12/29 Javascript
浅谈Javascript常用正则表达式应用
2019/03/08 Javascript
基于vue开发微信小程序mpvue-docs跳转页面功能
2019/04/10 Javascript
详解JavaScript 新语法之Class 的私有属性与私有方法
2019/04/23 Javascript
基于vue、react实现倒计时效果
2019/08/26 Javascript
vue选项卡切换登录方式小案例
2019/09/27 Javascript
javascript实现留言板功能
2020/02/08 Javascript
IDEA配置jQuery, $符号不再显示黄色波浪线的问题
2020/10/09 jQuery
python绘制直线的方法
2018/06/30 Python
django_orm查询性能优化方法
2018/08/20 Python
python移位运算的实现
2019/07/15 Python
8段用于数据清洗Python代码(小结)
2019/10/31 Python
python连接mysql数据库并读取数据的实现
2020/09/25 Python
全球领先的美容用品专卖店:Beauty Plus Salon
2018/09/04 全球购物
某个公司的Java笔面试题
2016/03/11 面试题
一篇.NET面试题
2014/09/29 面试题
什么是makefile? 如何编写makefile?
2012/08/08 面试题
德语专业求职信
2014/03/12 职场文书
合作协议书格式
2014/08/19 职场文书
支部书记四风问题对照检查材料
2014/10/04 职场文书
人大代表选举标语
2014/10/07 职场文书
老人再婚离婚协议书范本
2014/10/27 职场文书
2015年手术室工作总结
2015/05/11 职场文书
学习师德师风的心得体会(2篇)
2019/10/08 职场文书