Python FTP操作类代码分享

yipeiwu_com5年前Python基础

复制代码 代码如下:

#!/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()

相关文章

Pandas GroupBy对象 索引与迭代方法

如下所示: import pandas as pd df = pd.DataFrame({'性别' : ['男', '女', '男', '女', '男', '女',...

python处理html转义字符的方法详解

本文实例讲述了python处理html转义字符的方法。分享给大家供大家参考,具体如下: 最近在用Python处理网页数据时,经常遇到一些html转义字符(也叫html字符实体),例如&l...

详解Python中表达式i += x与i = i + x是否等价

详解Python中表达式i += x与i = i + x是否等价

前言 最近看到一个题目,看似很简单,其实里面有很深的意义,题目是Python 表达式 i += x 与 i = i + x 等价吗?如果你的回答是yes,那么恭喜你正确了50%,为什么说...

使用Python测试Ping主机IP和某端口是否开放的实例

使用Python测试Ping主机IP和某端口是否开放的实例

使用Python方法 比用各种命令方便,可以设置超时时间,到底通不通,端口是否开放一眼能看出来。 命令和返回 完整权限,可以ping通,端口开放,结果如下: 无root权限(省略了pi...

python中将正则过滤的内容输出写入到文件中的实例

处理过滤Apache日志文件 access_test.log文件内容 27.19.74.143 - - [30/May/2015:17:38:21 +0800] "GET /stat...