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实现以上的功能。