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求两个list的差集、交集与并集的方法
Nov 01 Python
python实现通过代理服务器访问远程url的方法
Apr 29 Python
详解Python 模拟实现生产者消费者模式的实例
Aug 10 Python
Python pymongo模块用法示例
Mar 31 Python
在python win系统下 打开TXT文件的实例
Apr 29 Python
pygame游戏之旅 添加游戏界面按键图形
Nov 20 Python
python利用openpyxl拆分多个工作表的工作簿的方法
Sep 27 Python
python实现机器人卡牌
Oct 06 Python
kafka-python 获取topic lag值方式
Dec 23 Python
pandas 强制类型转换 df.astype实例
Apr 09 Python
Python MOCK SERVER moco模拟接口测试过程解析
Apr 13 Python
Python获取指定日期是"星期几"的6种方法
Mar 13 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
php网站判断用户是否是手机访问的方法
2013/11/01 PHP
实例讲解php数据访问
2016/05/09 PHP
可输入的下拉框
2006/06/19 Javascript
jQuery 技巧大全(新手入门篇)
2009/05/12 Javascript
jQuery实现表单input中提示文字value随鼠标焦点移进移出而显示或隐藏的代码
2010/03/21 Javascript
DWZ刷新dialog解决方法
2013/03/03 Javascript
jquery实现图片裁剪思路及实现
2013/08/16 Javascript
在Firefox下js select标签点击无法弹出
2014/03/06 Javascript
js获取IP地址的方法小结
2014/07/01 Javascript
基于jQuery的图片不完全按比例自动缩小
2014/07/11 Javascript
javascript感应鼠标图片透明度显示的方法
2015/02/24 Javascript
SWFUpload多文件上传及文件个数限制的方法
2016/05/31 Javascript
Javascript基础_简单比较undefined和null 值
2016/06/14 Javascript
Vue 仿QQ左滑删除组件功能
2018/03/12 Javascript
vue实现分环境打包步骤(给不同的环境配置相对应的打包命令)
2019/06/04 Javascript
通过js给网页加上水印背景实例
2019/06/17 Javascript
js滚轮事件 js自定义滚动条的实现
2020/01/18 Javascript
JS数组索引检测中的数据类型问题详解
2021/01/11 Javascript
Python实现计算两个时间之间相差天数的方法
2017/05/10 Python
python中redis查看剩余过期时间及用正则通配符批量删除key的方法
2018/07/30 Python
Python3实现的回文数判断及罗马数字转整数算法示例
2019/03/27 Python
Django发送邮件和itsdangerous模块的配合使用解析
2019/08/10 Python
Python栈的实现方法示例【列表、单链表】
2020/02/22 Python
Python爬虫实例——爬取美团美食数据
2020/07/15 Python
python如何调用php文件中的函数详解
2020/12/29 Python
CSS3制作ajax loader icon实现思路及代码
2013/08/25 HTML / CSS
美国在线宠物商店:Chewy
2019/01/12 全球购物
SEPHORA丝芙兰德国官方购物网站:化妆品、护肤品和香水
2020/01/21 全球购物
自我评价范文
2013/12/22 职场文书
平面设计专业大学生职业规划书
2014/03/12 职场文书
工作会议主持词
2014/03/17 职场文书
煤矿安全演讲稿
2014/05/09 职场文书
群众路线专项整治工作情况报告
2014/10/28 职场文书
幼儿教师2014年度工作总结
2014/12/16 职场文书
python - asyncio异步编程
2021/04/06 Python
CentOS下安装Jenkins的完整步骤
2022/04/07 Servers