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脚本实现自动将数据库备份到 Dropbox
Feb 06 Python
Python实现判断一个字符串是否包含子串的方法总结
Nov 21 Python
简述Python2与Python3的不同点
Jan 21 Python
对python:print打印时加u的含义详解
Dec 15 Python
centos6.5安装python3.7.1之后无法使用pip的解决方案
Feb 14 Python
Pandas读取并修改excel的示例代码
Feb 17 Python
Python3中的bytes和str类型详解
May 02 Python
基于Python的图像数据增强Data Augmentation解析
Aug 13 Python
使用PyTorch将文件夹下的图片分为训练集和验证集实例
Jan 08 Python
Django ValuesQuerySet转json方式
Mar 16 Python
Python基于当前时间批量创建文件
May 07 Python
在Django中自定义filter并在template中的使用详解
May 19 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 XML操作的各种方法解析(比较详细)
2010/06/17 PHP
ThinkPHP整合百度Ueditor图文教程
2014/10/21 PHP
深入讲解PHP的Yii框架中的属性(Property)
2016/03/18 PHP
PHP array_reverse() 函数原理及实例解析
2020/07/14 PHP
php7连接MySQL实现简易查询程序的方法
2020/10/13 PHP
JavaScript触发器详解
2007/03/10 Javascript
javascript Array.remove() 数组删除
2009/08/06 Javascript
使用JS 清空File控件的路径值
2013/07/08 Javascript
分享使用AngularJS创建应用的5个框架
2015/12/05 Javascript
js调出上下文菜单的实例
2015/12/17 Javascript
Bootstrap模态框调用功能实现方法
2016/09/19 Javascript
利用vue实现模态框组件
2016/12/19 Javascript
Bootstrap 模态框(Modal)插件代码解析
2016/12/21 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
angularJS自定义directive之带参方法传递详解
2018/10/09 Javascript
详解关于element el-button使用$attrs的一个注意要点
2018/11/09 Javascript
JS遍历JSON数组及获取JSON数组长度操作示例【测试可用】
2018/12/12 Javascript
详解vue配置后台接口方式
2019/03/29 Javascript
微信小程序访问豆瓣电影api的实现方法
2019/03/31 Javascript
JavaScript回调函数callback用法解析
2020/01/14 Javascript
uni-app使用countdown插件实现倒计时
2020/11/01 Javascript
[01:34:42]NAVI vs EG 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
wxpython 学习笔记 第一天
2009/03/16 Python
Python实现将n个点均匀地分布在球面上的方法
2015/03/12 Python
Python中字典映射类型的学习教程
2015/08/20 Python
tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法
2018/07/27 Python
HTML5 新表单类型示例代码
2018/03/20 HTML / CSS
西班牙太阳镜品牌:Hawkers
2018/03/11 全球购物
后勤人员自我鉴定
2013/10/20 职场文书
2013年军训通讯稿
2014/02/05 职场文书
出纳员的岗位职责
2014/02/22 职场文书
鉴定评语大全
2014/05/05 职场文书
党支部反对四风思想汇报
2014/10/10 职场文书
2014年流动人口工作总结
2014/11/26 职场文书
如何用H5实现好玩的2048小游戏
2022/07/23 HTML / CSS
win10壁纸在哪个文件夹 win10桌面背景图片文件位置分享
2022/08/05 数码科技