Python中FTP的使用

  FTP在各種應用中經常出現,Python也提供了相應的庫:ftplib。

#!/usr/bin/python
import sys,os
import ftplib
class ftpClient:
    def __init__(self, logger):
        self.logger = logger
        self.ftp = None
    def connect(self, ftpServerIp, userName, password, timeout=1000, ftpPort=21):
        try:
            self.ftp = ftplib.FTP()
            self.ftp.connect(ftpServerIp, ftpPort, timeout)
            self.ftp.login(userName, password)
        except Exception, exInfo:
            logInfo = "Connect FTP server failed: [%s]" %exInfo
            self.logger.error(logInfo)
    def disconnect(self):
        try:
            if self.ftp:
                self.ftp.quit()
        except Exception, exInfo:
            logInfo = "Disconnect FTP server failed: [%s]" %exInfo
            self.logger.error(logInfo)
    def list(self, dir):
        fileList = []
        try:
            self.ftp.cwd(dir)
            fileList = self.ftp.nlst()
        except Exception, exInfo:
            logInfo = "List [%s] failed: [%s]" %(dir, exInfo)
            self.logger.error(logInfo)
        return fileList
    def upload(self, filePath):
        uploadFlag = False
        try:
            BUFFER_SIZE = 8192
            fileReader = open(filePath, "rb")
            fileName = os.path.split(filePath)[-1]
            self.ftp.storbinary('STOR %s' %fileName, fileReader, BUFFER_SIZE)
            fileReader.close()
            uploadFlag = True
        except Exception, exInfo:
            logInfo = "Upload [%s] failed: [%s]" %(filePath, exInfo)
            self.logger.error(logInfo)
        return uploadFlag
    def download(self, fileName, localPath, delFlag=False):
        downloadFlag = False
        try:
            localFile = os.path.join(localPath, fileName)
            fileWriter = open(localFile, 'wb')
            self.ftp.retrbinary('RETR %s' %fileName, fileWriter.write)
            fileWriter.close()
            if delFlag: self.ftp.delete(fileName)
            downloadFlag = True
        except Exception, exInfo:
            logInfo = "Download [%s] failed: [%s]" %(fileName, exInfo)
            self.logger.error(logInfo)
        return downloadFlag

  當然,也可以在Python中調用jar實現以上的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章