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 相关文章推荐
Python2.7简单连接与操作MySQL的方法
Apr 27 Python
python买卖股票的最佳时机(基于贪心/蛮力算法)
Jul 05 Python
python3实现的zip格式压缩文件夹操作示例
Aug 17 Python
Python 简单计算要求形状面积的实例
Jan 18 Python
Python列表操作方法详解
Feb 09 Python
Python 实现日志同时输出到屏幕和文件
Feb 19 Python
python模拟点击网页按钮实现方法
Feb 25 Python
python上传时包含boundary时的解决方法
Apr 08 Python
Python+Django+MySQL实现基于Web版的增删改查的示例代码
May 13 Python
浅谈优化Django ORM中的性能问题
Jul 09 Python
Python安装Bs4的多种方法
Nov 28 Python
Python序列化模块JSON与Pickle
Jun 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
PHP6 mysql连接方式说明
2009/02/09 PHP
php多维数组去掉重复值示例分享
2014/03/02 PHP
php调整服务器时间的方法
2015/04/03 PHP
基于jQuery实现的文字按钮表单特效整理
2014/12/07 Javascript
APP中javascript+css3实现下拉刷新效果
2016/01/27 Javascript
jQuery插件开发汇总
2016/05/15 Javascript
jquery选择器中的空格与大于号>、加号+与波浪号~的区别介绍
2016/06/24 Javascript
JavaScript实现两个select下拉框选项左移右移
2017/03/09 Javascript
原生JavaScript来实现对dom元素class的操作方法(推荐)
2017/08/16 Javascript
微信小程序实现动态设置页面标题的方法【附源码下载】
2017/11/29 Javascript
jQuery实现手机号正则验证输入及自动填充空格功能
2018/01/02 jQuery
浅析JS中什么是自定义react数据验证组件
2018/10/19 Javascript
django使用channels2.x实现实时通讯
2018/11/28 Javascript
mpvue实现微信小程序快递单号查询代码
2020/04/03 Javascript
[01:32]DOTA2上海特锦赛现场采访:最想COS的英雄
2016/03/25 DOTA
python通过pil将图片转换成黑白效果的方法
2015/03/16 Python
django+js+ajax实现刷新页面的方法
2017/05/22 Python
Python编写登陆接口的方法
2017/07/10 Python
Python实现线程状态监测简单示例
2018/03/28 Python
Python Django实现layui风格+django分页功能的例子
2019/08/29 Python
给大家整理了19个pythonic的编程习惯(小结)
2019/09/25 Python
基于python图书馆管理系统设计实例详解
2020/08/05 Python
Python中qutip用法示例详解
2020/10/02 Python
Python eval函数介绍及用法
2020/11/09 Python
基于Jquery和Css3代码制作可以缩放的搜索框
2015/11/19 HTML / CSS
LEGO玩具英国官方商店:LEGO Shop GB
2018/03/27 全球购物
英国第一的滑雪服装和装备零售商:Snow+Rock
2020/02/01 全球购物
了解AppleShare protocol(AppleShare协议)吗
2015/08/28 面试题
上海期货面试题
2014/01/31 面试题
施工质量承诺书范文
2014/05/30 职场文书
以幸福为主题的活动方案
2014/08/22 职场文书
2016年秋季开学典礼新闻稿
2015/11/25 职场文书
《水浒传》读后感3篇(范文)
2019/09/19 职场文书
解决vue $http的get和post请求跨域问题
2021/06/07 Vue.js
Python中OpenCV实现简单车牌字符切割
2021/06/11 Python
Python读写yaml文件
2022/03/20 Python