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的一些用法分享
Oct 07 Python
Python升级提示Tkinter模块找不到的解决方法
Aug 22 Python
python使用socket连接远程服务器的方法
Apr 29 Python
numpy中矩阵合并的实例
Jun 15 Python
mac安装pytorch及系统的numpy更新方法
Jul 26 Python
Python实现的简单计算器功能详解
Aug 25 Python
python实现图片二值化及灰度处理方式
Dec 07 Python
python numpy--数组的组合和分割实例
Feb 24 Python
python如何从键盘获取输入实例
Jun 18 Python
Python txt文件常用读写操作代码实例
Aug 03 Python
python实现按日期归档文件
Jan 30 Python
总结Pyinstaller打包的高级用法
Jun 28 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
ASP知识讲座四
2006/10/09 PHP
PHP4实际应用经验篇(1)
2006/10/09 PHP
PHP 数组基础知识小结
2010/08/20 PHP
利用PHP实现智能文件类型检测的实现代码
2011/08/02 PHP
也说JavaScript中String类的replace函数
2011/09/22 Javascript
jquery操作checked属性以及disabled属性的多种方法
2014/06/20 Javascript
javascript比较两个日期的先后示例代码
2014/12/31 Javascript
移除AngularJS下URL中的#字符的方法
2015/06/19 Javascript
JS模拟实现Select效果代码
2015/09/24 Javascript
javascript生成img标签的3种实现方法(对象、方法、html)
2015/12/25 Javascript
JavaScript使用Range调色及透明度实例
2016/09/25 Javascript
Web前端开发之水印、图片验证码
2016/11/27 Javascript
node.js基础知识小结
2018/02/26 Javascript
微信小程序点击保存图片到本机功能
2019/12/13 Javascript
JS如何实现网站中PC端和手机端自动识别并跳转对应的代码
2020/01/08 Javascript
js实现mp3录音通过websocket实时传送+简易波形图效果
2020/06/12 Javascript
JavaScript实现网页tab栏效果制作
2020/11/20 Javascript
[42:24]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第三场 11.27
2020/12/01 DOTA
Python中DJANGO简单测试实例
2015/05/11 Python
python+VTK环境搭建及第一个简单程序代码
2017/12/13 Python
查看Django和flask版本的方法
2018/05/14 Python
使用Python实现跳帧截取视频帧
2019/05/31 Python
python图像处理模块Pillow的学习详解
2019/10/09 Python
Python with语句和过程抽取思想
2019/12/23 Python
Python selenium 自动化脚本打包成一个exe文件(推荐)
2020/01/14 Python
k-means 聚类算法与Python实现代码
2020/06/01 Python
Skyscanner波兰:廉价航班
2017/11/07 全球购物
Notino匈牙利:购买香水和化妆品
2019/04/12 全球购物
客服服务心得体会
2013/12/30 职场文书
九年级化学教学反思
2014/01/28 职场文书
村级个人对照检查材料
2014/08/22 职场文书
女儿满月酒致辞
2015/07/29 职场文书
《颐和园》教学反思
2016/02/19 职场文书
七年级思品教学反思
2016/02/20 职场文书
推荐六本经典文学奖书籍:此生必读
2019/08/22 职场文书
Python深度学习之实现卷积神经网络
2021/06/05 Python