Python FTP操作类代码分享


Posted in Python onMay 13, 2014
#!/usr/bin/py2
# -*- coding: utf-8 -*-
#encoding=utf-8
'''''
    ftp自动下载、自动上传脚本,可以递归目录操作
'''  
from ftplib import FTP
import os, sys, string, datetime, time
import socket   
class FtpClient:
    def __init__(self, host, user, passwd, remotedir, port=21):
        self.hostaddr = host
        self.username = user
        self.password = passwd
        self.remotedir  = remotedir           
        self.port     = port
        self.ftp      = FTP()
        self.file_list = []   
    def __del__(self):
        self.ftp.close()   
    def login(self):
        ftp = self.ftp
        try:
            timeout = 60
            socket.setdefaulttimeout(timeout)
            ftp.set_pasv(True)
            ftp.connect(self.hostaddr, self.port)
            print 'Connect Success %s' %(self.hostaddr)
            ftp.login(self.username, self.password)
            print 'Login Success %s' %(self.hostaddr)
            debug_print(ftp.getwelcome())
        except Exception:
            deal_error("Connect Error or Login Error")
        try:
            ftp.cwd(self.remotedir)
        except(Exception):
            deal_error('Change Directory Error')   
    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('lo:%d  re:%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):
            return
        else:
            pass
        file_handler = open(localfile, 'wb')
        self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
        file_handler.close()
    def download_files(self, localdir='./', remotedir='./'):
        try:
            self.ftp.cwd(remotedir)
        except:
            return
        if not os.path.isdir(localdir):
            os.makedirs(localdir)
        self.file_list = []
        self.ftp.dir(self.get_file_list)
        remotenames = self.file_list
        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('..')   
    def upload_file(self, localfile, remotefile):
        if not os.path.isfile(localfile):
            return
        if self.is_same_size(localfile, remotefile):
            return
        file_handler = open(localfile, 'rb')
        self.ftp.storbinary('STOR %s' %remotefile, file_handler)
        file_handler.close()   
    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('Directory Exists %s' %item)
                self.upload_files(src, item)
            else:
                self.upload_file(src, item)
        self.ftp.cwd('..')
    def mkdir(self, remotedir='./'):
        try:
            self.ftp.mkd(remotedir)
        except:
            debug_print('Directory Exists %s' %remotedir)
    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(str):
    print (str)
def deal_error(e):
    timenow  = time.localtime()
    datenow  = time.strftime('%Y-%m-%d', timenow)
    logstr = '%s Error: %s' %(datenow, e)
    debug_print(logstr)
    file.write(logstr)
    sys.exit()
Python 相关文章推荐
python自动化测试实例解析
Sep 28 Python
Django rest framework基本介绍与代码示例
Jan 26 Python
Windows下安装Django框架的方法简明教程
Mar 28 Python
Python文本统计功能之西游记用字统计操作示例
May 07 Python
Python线性拟合实现函数与用法示例
Dec 13 Python
详解Python_shutil模块
Mar 15 Python
Falsk 与 Django 过滤器的使用与区别详解
Jun 04 Python
Django Rest framework频率原理与限制
Jul 26 Python
Python列表list常用内建函数实例小结
Oct 22 Python
浅析Python3 pip换源问题
Jan 06 Python
Python3读取和写入excel表格数据的示例代码
Jun 09 Python
python语言中pandas字符串分割str.split()函数
Aug 05 Python
python生成指定尺寸缩略图的示例
May 07 #Python
python读取浮点数和读取文本文件示例
May 06 #Python
python创建线程示例
May 06 #Python
Python Web服务器Tornado使用小结
May 06 #Python
Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
May 06 #Python
Python Web开发模板引擎优缺点总结
May 06 #Python
windows系统中python使用rar命令压缩多个文件夹示例
May 06 #Python
You might like
关于Yii2框架跑脚本时内存泄漏问题的分析与解决
2019/12/01 PHP
DOM 脚本编程中的兄弟节点
2009/10/31 Javascript
基于jquery的给文章加入关键字链接
2010/10/26 Javascript
node.js中的fs.futimes方法使用说明
2014/12/17 Javascript
浅谈javascript中replace()方法
2015/11/10 Javascript
JavaScript对象数组排序函数及六个用法
2015/12/23 Javascript
JQuery组件基于Bootstrap的DropDownList(完整版)
2016/07/05 Javascript
关于数据与后端进行交流匹配(点亮星星)
2016/08/03 Javascript
基本DOM节点操作
2017/01/17 Javascript
javaScript基础详解
2017/01/19 Javascript
js实现滑动到页面底部自动加载更多功能
2017/02/15 Javascript
Vue.js结合Ueditor富文本编辑器的实例代码
2017/07/11 Javascript
JS实现简单的选择题测评系统代码思路详解(demo)
2017/09/03 Javascript
JS设计模式之命令模式概念与用法分析
2018/02/06 Javascript
解决Layui数据表格中checkbox位置不居中的方法
2018/08/15 Javascript
C#程序员入门学习微信小程序的笔记
2019/03/05 Javascript
从理论角度讨论JavaScript闭包
2019/04/03 Javascript
javascript实现打砖块小游戏(附完整源码)
2020/09/18 Javascript
微信小程序反编译的实现
2020/12/10 Javascript
Python使用scrapy采集数据过程中放回下载过大页面的方法
2015/04/08 Python
Python中强大的命令行库click入门教程
2016/12/26 Python
用Python将Excel数据导入到SQL Server的例子
2019/08/24 Python
关于Python 常用获取元素 Driver 总结
2019/11/24 Python
python上传时包含boundary时的解决方法
2020/04/08 Python
Python异常处理机制结构实例解析
2020/07/23 Python
python实现启动一个外部程序,并且不阻塞当前进程
2020/12/05 Python
ABOUT YOU匈牙利:500个最受欢迎的时尚品牌
2019/07/19 全球购物
施华洛世奇巴西官网:SWAROVSKI巴西
2019/12/03 全球购物
如何删除一个表里面的重复行
2013/07/13 面试题
毕业生求职简历的自我评价
2013/10/23 职场文书
户籍证明格式
2014/09/15 职场文书
教师党员个人自我剖析材料
2014/09/29 职场文书
领导干部作风建设自查报告
2014/10/23 职场文书
长城导游词400字
2015/01/30 职场文书
学习商务礼仪心得体会
2016/01/22 职场文书
vue如何实现关闭对话框后刷新列表
2022/04/08 Vue.js