Python FTP操作类代码分享

时间:2022-09-07 17:59:23 


#!/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,FTP
0
投稿

猜你喜欢

  • Python协程实践分享

    2023-09-01 05:50:51
  • 详解python3 GUI刷屏器(附源码)

    2022-02-02 12:34:15
  • 解析ROC曲线绘制(python+sklearn+多分类)

    2021-04-06 12:16:16
  • 总结Python图形用户界面和游戏开发知识点

    2022-03-03 18:36:25
  • Python 虚拟机字典dict内存优化方法解析

    2022-03-04 08:20:56
  • Python 继承,重写,super()调用父类方法操作示例

    2022-08-09 13:22:13
  • Python基础语法(Python基础知识点)

    2021-03-04 11:10:34
  • Python列表对象中元素的删除操作方法

    2023-11-12 01:09:22
  • 番茄的js表单验证类

    2008-01-07 13:53:00
  • 浅析Python 中的 WSGI 接口和 WSGI 服务的运行

    2023-02-18 14:45:40
  • 详解Python中的Descriptor描述符类

    2021-10-16 10:10:35
  • Python实现手写一个类似django的web框架示例

    2022-06-18 03:17:26
  • Web脚本开发语言比较

    2007-08-22 17:32:00
  • asp查询xml的代码 不刷新页面查询的方法

    2011-04-06 11:00:00
  • Python字符编码转码之GBK,UTF8互转

    2023-02-20 14:03:01
  • br玩转清除浮动

    2007-05-11 16:52:00
  • Linux+php+apache+oracle环境搭建之CentOS下安装Oracle数据库

    2023-10-08 01:02:56
  • python实现从ftp服务器下载文件的方法

    2023-08-02 20:50:54
  • Django渲染Markdown文章目录的方法示例

    2021-03-31 05:12:07
  • 实例讲解python函数式编程

    2022-10-30 22:14:35
  • asp之家 网络编程 m.aspxhome.com