编写Python脚本来实现最简单的FTP下载的教程

yipeiwu_com6年前Python基础

访问FTP,无非两件事情:upload和download,最近在项目中需要从ftp下载大量文件,然后我就试着去实验自己的ftp操作类,如下(PS:此段有问题,别复制使用,可以参考去试验自己的ftp类!)

import os
from ftplib import FTP
 
class FTPSync():
  def __init__(self, host, usr, psw, log_file):
    self.host = host
    self.usr = usr
    self.psw = psw
    self.log_file = log_file
   
  def __ConnectServer(self):
    try:
      self.ftp = FTP(self.host)
      self.ftp.login(self.usr, self.psw)
      self.ftp.set_pasv(False)
      return True
    except Exception:
      return False
   
  def __CloseServer(self):
    try:
      self.ftp.quit()
      return True
    except Exception:
      return False
   
  def __CheckSizeEqual(self, remoteFile, localFile):
    try:
      remoteFileSize = self.ftp.size(remoteFile)
      localFileSize = os.path.getsize(localFile)
      if localFileSize == remoteFileSize:
        return True
      else:
        return False
    except Exception:
      return None
     
  def __DownloadFile(self, remoteFile, localFile):
    try:
      self.ftp.cwd(os.path.dirname(remoteFile))
      f = open(localFile, 'wb')
      remoteFileName = 'RETR ' + os.path.basename(remoteFile)
      self.ftp.retrbinary(remoteFileName, f.write)
       
      if self.__CheckSizeEqual(remoteFile, localFile):
        self.log_file.write('The File is downloaded successfully to %s' + '\n' % localFile)
        return True
      else:
        self.log_file.write('The localFile %s size is not same with the remoteFile' + '\n' % localFile)
        return False
    except Exception:
      return False
   
  def __DownloadFolder(self, remoteFolder, localFolder):
    try:
      fileList = []
      self.ftp.retrlines('NLST', fileList.append)
      for remoteFile in fileList:
        localFile = os.path.join(localFolder, remoteFile)
        return self.__DownloadFile(remoteFile, localFile)
    except Exception:
      return False
   
  def SyncFromFTP(self, remoteFolder, localFolder):
    self.__DownloadFolder(remoteFolder, localFolder)
    self.log_file.close()
    self.__CloseServer()

相关文章

深入学习python的yield和generator

前言 没有用过的东西,没有深刻理解的东西很难说自己会,而且被别人一问必然破绽百出。虽然之前有接触过python协程的概念,但是只是走马观花,这两天的一次交谈中,别人问到了协程,顿时语塞,...

Python面向对象之接口、抽象类与多态详解

本文实例讲述了Python面向对象之接口、抽象类与多态。分享给大家供大家参考,具体如下: 接口类 继承有两种用途: 一:继承基类的方法,并且做出自己的改变或者扩展(代码重用) 二:声明某...

Python网站验证码识别

Python网站验证码识别

0x00 识别涉及技术 验证码识别涉及很多方面的内容。入手难度大,但是入手后,可拓展性又非常广泛,可玩性极强,成就感也很足。 验证码图像处理 验证码图像识别技术主要是操作图片内的像素点,...

Python使用pyh生成HTML文档的方法示例

Python使用pyh生成HTML文档的方法示例

最近在项目中需要将结果导出到HTML中,在网上搜索的时候发现了这个库,通过官方的一些文档以及网上的博客发现它的使用还是很简单的,因此选择在项目中使用它。 在使用的时候发现在Python3...

Python自动化运维之IP地址处理模块详解

实用的IP地址处理模块IPy 在IP地址规划中,涉及到计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等 别担心,Ipy模块拯救你。Ipy模块可以很好的辅助我们高效的...