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动态加载模块的3种方法
Nov 22 Python
Python中强大的命令行库click入门教程
Dec 26 Python
python fabric实现远程部署
Jan 05 Python
Win10下python3.5和python2.7环境变量配置教程
Sep 18 Python
Python告诉你木马程序的键盘记录原理
Feb 02 Python
python aiohttp的使用详解
Jun 20 Python
python将时分秒转换成秒的实例
Dec 07 Python
python操作cfg配置文件方式
Dec 22 Python
win10下python2和python3共存问题解决方法
Dec 23 Python
pycharm 更改创建文件默认路径的操作
Feb 15 Python
django 扩展user用户字段inlines方式
Mar 30 Python
Python排序算法之插入排序及其优化方案详解
Jun 11 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
什么是短波收听SWL
2021/03/01 无线电
openPNE常用方法分享
2011/11/29 PHP
php通过array_merge()函数合并两个数组的方法
2015/03/18 PHP
PHP+Javascript实现在线拍照功能实例
2015/07/18 PHP
关于php支持的协议与封装协议总结(推荐)
2017/11/17 PHP
Laravel核心解读之异常处理的实践过程
2019/02/24 PHP
PHP使用gearman进行异步的邮件或短信发送操作详解
2020/02/27 PHP
用户注册常用javascript代码
2009/08/29 Javascript
JavaScript 更严格的相等 [译]
2012/09/20 Javascript
JS鼠标滑过图片时切换图片实现思路
2013/09/12 Javascript
javascript页面加载完执行事件代码
2014/02/11 Javascript
浅析JavaScript动画
2015/06/10 Javascript
jquery中键盘事件小结
2016/02/24 Javascript
jQuery实现鼠标经过购物车出现下拉框代码(推荐)
2016/07/21 Javascript
关于Vue中axios的封装实例详解
2019/10/20 Javascript
你知道JavaScript Symbol类型怎么用吗
2020/01/08 Javascript
ES6 十大特性简介
2020/12/09 Javascript
[01:11]辉夜杯战队访谈宣传片—CDEC.Y
2015/12/26 DOTA
整理Python 常用string函数(收藏)
2016/05/30 Python
python调用Matplotlib绘制分布点并且添加标签
2018/05/31 Python
python实现决策树分类
2018/08/30 Python
python简单验证码识别的实现方法
2019/05/10 Python
Python 实现数据结构-堆栈和队列的操作方法
2019/07/17 Python
python GUI库图形界面开发之PyQt5布局控件QVBoxLayout详细使用方法与实例
2020/03/06 Python
解决python多线程报错:AttributeError: Can't pickle local object问题
2020/04/08 Python
django 将自带的数据库sqlite3改成mysql实例
2020/07/09 Python
路易威登和香奈儿手袋:LuxeDH
2017/01/12 全球购物
写出一个方法实现冒泡排序
2016/07/08 面试题
法律专业个人实习自我鉴定
2013/09/23 职场文书
大学生自我鉴定范文模板
2014/01/21 职场文书
校园安全广播稿
2014/02/08 职场文书
报表员工作失误检讨书范文
2014/09/19 职场文书
幼儿园教师考核评语
2014/12/31 职场文书
创建文明城市倡议书
2015/04/28 职场文书
如何理解及使用Python闭包
2021/06/01 Python
用JS写一个发布订阅模式
2021/11/07 Javascript