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多进程机制实例详解
Jul 02 Python
在Django的视图(View)外使用Session的方法
Jul 23 Python
浅谈Python用QQ邮箱发送邮件时授权码的问题
Jan 29 Python
利用Python在一个文件的头部插入数据的实例
May 02 Python
python中多个装饰器的执行顺序详解
Oct 08 Python
基于python实现名片管理系统
Nov 30 Python
Django使用模板后无法找到静态资源文件问题解决
Jul 19 Python
python Django编写接口并用Jmeter测试的方法
Jul 31 Python
深入了解python中元类的相关知识
Aug 29 Python
Python中的xlrd模块使用原理解析
May 21 Python
Python join()函数原理及使用方法
Nov 14 Python
使用Python爬取小姐姐图片(beautifulsoup法)
Feb 11 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站内搜索并高亮显示关键字的实现代码
2011/12/29 PHP
如何获知PHP程序占用多少内存(memory_get_usage)
2012/09/23 PHP
php内核解析:PHP中的哈希表
2014/01/30 PHP
解决cPanel无法安装php5.2.17
2014/06/22 PHP
PHP基于DateTime类解决Unix时间戳与日期互转问题【针对1970年前及2038年后时间戳】
2018/06/13 PHP
详解php中生成标准uuid(guid)的方法
2019/04/28 PHP
JavaScript-世界上误解最深的语言分析
2007/08/12 Javascript
CSS常用网站布局实例
2008/04/03 Javascript
关于JavaScript的一些看法
2009/05/27 Javascript
jQuery JSON的解析方式分享
2011/04/05 Javascript
javascript实现简单的鼠标拖动效果实例
2015/04/10 Javascript
jquery捕捉回车键及获取checkbox值与异步请求的方法
2015/12/24 Javascript
图片上传之FileAPI与NodeJs
2017/01/24 NodeJs
Node.JS利用PhantomJs抓取网页入门教程
2017/05/19 Javascript
基于BootStrap multiselect.js实现的下拉框联动效果
2017/07/28 Javascript
使用JS实现导航切换时高亮显示的示例讲解
2018/08/22 Javascript
vue+koa2搭建mock数据环境的详细教程
2020/05/18 Javascript
jQuery 选择方法及$(this)用法实例分析
2020/05/19 jQuery
如何在JavaScript中等分数组的实现
2020/12/13 Javascript
Python二分法搜索算法实例分析
2015/05/11 Python
Python IDE PyCharm的基本快捷键和配置简介
2015/11/04 Python
python 3.5下xadmin的使用及修复源码bug
2017/05/10 Python
Python3解决棋盘覆盖问题的方法示例
2017/12/07 Python
Python单元测试unittest的具体使用示例
2018/12/17 Python
pandas DataFrame 删除重复的行的实现方法
2019/01/29 Python
Python中请不要再用re.compile了
2019/06/30 Python
pandas DataFrame的修改方法(值、列、索引)
2019/08/02 Python
Python3多线程版TCP端口扫描器
2019/08/31 Python
python获取全国城市pm2.5、臭氧等空气质量过程解析
2019/10/12 Python
OpenCV python sklearn随机超参数搜索的实现
2020/01/17 Python
解决python多线程报错:AttributeError: Can't pickle local object问题
2020/04/08 Python
Python爬取YY评级分数并保存数据实现过程解析
2020/06/01 Python
如何给HTML标签中的文本设置修饰线
2019/11/18 HTML / CSS
英国办公家具网站:Furniture At Work
2019/10/07 全球购物
《难忘的泼水节》教学反思
2014/02/27 职场文书
导游词之西江千户苗寨
2019/12/24 职场文书