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)操作方法汇总
Aug 18 Python
Centos Python2 升级到Python3的简单实现
Jun 21 Python
详谈Python2.6和Python3.0中对除法操作的异同
Apr 28 Python
Python opencv实现人眼/人脸识别以及实时打码处理
Apr 29 Python
python自动化之Ansible的安装教程
Jun 13 Python
基于Python2、Python3中reload()的不同用法介绍
Aug 12 Python
python中class的定义及使用教程
Sep 18 Python
通过实例解析Python return运行原理
Mar 04 Python
用python打开摄像头并把图像传回qq邮箱(Pyinstaller打包)
May 17 Python
完美解决TensorFlow和Keras大数据量内存溢出的问题
Jul 03 Python
Python中三维坐标空间绘制的实现
Sep 22 Python
Python3爬虫ChromeDriver的安装实例
Feb 06 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中调用JAVA
2006/10/09 PHP
PHP的面向对象编程
2006/10/09 PHP
php采集时被封ip的解决方法
2010/08/29 PHP
《PHP编程最快明白》第七讲:php图片验证码与缩略图
2010/11/01 PHP
php中有关字符串的4个函数substr、strrchr、strstr、ereg介绍和使用例子
2014/04/24 PHP
ThinkPHP查询中的魔术方法简述
2014/06/25 PHP
Thinkphp5行为使用方法汇总
2017/12/21 PHP
JavaScript实现GriwView单列全选(自写代码)
2013/05/13 Javascript
jQuery中append()方法用法实例
2014/12/25 Javascript
javascript实现控制文字大中小显示
2015/04/28 Javascript
jQuery实现类似标签风格的导航菜单效果代码
2015/08/25 Javascript
js实现文件上传表单域美化特效
2015/11/02 Javascript
JS使用post提交的两种方式
2015/12/03 Javascript
javascript拖拽效果延伸学习
2016/04/04 Javascript
完美解决jQuery符号$与其他javascript 库、框架冲突的问题
2016/08/09 Javascript
js实现音乐播放控制条
2017/09/09 Javascript
vue脚手架及vue-router基本使用
2018/04/09 Javascript
JavaScript常用数组操作方法,包含ES6方法
2020/05/10 Javascript
深入浅析javascript函数中with
2018/10/28 Javascript
vue开发中遇到的问题总结
2020/04/07 Javascript
vue实现分页的三种效果
2020/06/23 Javascript
[01:50]《我与DAC》之玩家:iG夺冠时的那面红旗
2018/03/29 DOTA
Python数据分析之双色球统计单个红和蓝球哪个比例高的方法
2018/02/03 Python
Python神奇的内置函数locals的实例讲解
2019/02/22 Python
Python实现的列表排序、反转操作示例
2019/03/13 Python
Python ellipsis 的用法详解
2020/11/20 Python
python中time、datetime模块的使用
2020/12/14 Python
Sephora丝芙兰泰国官方网站:国际知名化妆品购物
2017/11/15 全球购物
微软台湾官方网站:Microsoft台湾
2018/08/15 全球购物
会计系个人求职信范文分享
2013/12/20 职场文书
演讲稿格式范文
2014/05/19 职场文书
教师党员先进性教育自我剖析材料思想汇报
2014/09/24 职场文书
机关作风建设工作总结
2014/10/23 职场文书
学生会个人总结范文
2015/02/15 职场文书
mysql的单列多值存储实例详解
2022/04/05 MySQL
Golang连接并操作MySQL
2022/04/14 MySQL