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的MongoDB模块PyMongo操作方法集锦
Jan 05 Python
关于Python元祖,列表,字典,集合的比较
Jan 06 Python
python 遍历字符串(含汉字)实例详解
Apr 04 Python
Python3 处理JSON的实例详解
Oct 29 Python
python基于物品协同过滤算法实现代码
May 31 Python
Python异常处理操作实例详解
Aug 28 Python
pandas 透视表中文字段排序方法
Nov 16 Python
PyTorch的Optimizer训练工具的实现
Aug 18 Python
详解用Python为直方图绘制拟合曲线的两种方法
Aug 21 Python
Python 读取 YUV(NV12) 视频文件实例
Dec 09 Python
python3.6.5基于kerberos认证的hive和hdfs连接调用方式
Jun 06 Python
还在手动盖楼抽奖?教你用Python实现自动评论盖楼抽奖(一)
Jun 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
phpBB BBcode处理的漏洞
2006/10/09 PHP
用libtemplate实现静态网页生成
2006/10/09 PHP
php adodb操作mysql数据库
2009/03/19 PHP
如何设置mysql允许外网访问
2013/06/04 PHP
PHP使用正则表达式清除超链接文本
2013/11/12 PHP
PHP通过插入mysql数据来实现多机互锁实例
2014/11/05 PHP
PHP统计当前在线用户数实例讲解
2015/10/21 PHP
PHP简单获取及判断提交来源的方法
2016/04/22 PHP
PHP Laravel 上传图片、文件等类封装
2017/08/16 PHP
php使用filter_var函数判断邮箱,url,ip格式示例
2019/07/06 PHP
JQuery+CSS提示框实现思路及代码(纯手工打造)
2013/05/07 Javascript
javascript获取函数名称、函数参数、对象属性名称的代码实例
2014/04/12 Javascript
JSON+HTML实现国家省市联动选择效果
2014/05/18 Javascript
浅析JavaScript 箭头函数 generator Date JSON
2016/05/23 Javascript
动态加载js、css的实例代码
2016/05/26 Javascript
图文详解JavaScript的原型对象及原型链
2016/08/02 Javascript
gulp-uglify 与gulp.watch()配合使用时报错(重复压缩问题)
2016/08/24 Javascript
nodejs中密码加密处理操作详解
2018/03/20 NodeJs
vue中$set的使用(结合在实际应用中遇到的坑)
2018/07/10 Javascript
js通过循环多张图片实现动画效果
2019/12/19 Javascript
[04:01]2014DOTA2国际邀请赛 TITAN告别Ohaiyo期望明年再战
2014/07/15 DOTA
python-视频分帧&多帧合成视频实例
2019/12/10 Python
python爬虫实现爬取同一个网站的多页数据的实例讲解
2021/01/18 Python
python切片作为占位符使用实例讲解
2021/02/17 Python
CSS3实现任意图片lowpoly动画效果实例
2017/05/11 HTML / CSS
HTML5 Canvas阴影使用方法实例演示
2013/08/02 HTML / CSS
html5 datalist标签使用示例(自动完成组件)
2014/05/04 HTML / CSS
国际知名军事风格休闲装品牌:Alpha Industries(阿尔法工业)
2017/05/24 全球购物
全球速卖通法国在线交易平台:AliExpress法国
2017/07/07 全球购物
专门经营化妆刷的美国彩妆品牌:Sigma Beauty
2017/09/11 全球购物
伯利陶器:Burleigh Pottery
2018/01/03 全球购物
大学竞选班干部演讲稿
2014/08/21 职场文书
如何在C++中调用Python
2021/05/21 Python
python四种出行路线规划的实现
2021/06/23 Python
MySQL8.0升级的踩坑历险记
2021/11/01 MySQL
JavaScript原型链详解
2021/11/07 Javascript