python下載ftp檔案指令碼
阿新 • • 發佈:2020-11-06
最近更新日期:2020/11/6
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: [email protected] # Date: 2020/8/20 import logging import time import datetime import os # 日誌配置 workdir=os.path.dirname(os.path.realpath(__file__)) logdir=workdir+'/logs' isExists=os.path.exists(logdir) if not isExists: os.makedirs(logdir) logfile = logdir+'/' + 'log_'+os.path.basename(__file__).split('.')[0]+".log" os.chdir(workdir) logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler(logfile,mode='w') handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) defget_day(day_str=time.strftime('%Y-%m-%d'),day_offset=0): day_str=day_str.replace('-','').replace('/','') v_cur_day=datetime.datetime.strptime(day_str,'%Y%m%d') v_day=v_cur_day+datetime.timedelta(days=day_offset) return v_day.strftime('%Y-%m-%d') cur_day=get_day() pre_day=get_day(day_offset=-1) logger.info("開始執行...") from ftplib import FTP IP="192.168.6.149" user="ftp" password="1111" ftp=FTP() #ftp.set_debuglevel(2) ftp.connect(IP) ftp.login(user,password) #print ftp.getwelcome() # 使用主動模式,只需開通訪問服務端 20 和 21埠訪問 ftp.set_pasv(False) #upload #ftp.storbinary('STOR %s' %filename, open(path,'rb',8192)) #download cur_day=get_day().replace('-','') pre_day=get_day(day_offset=-1).replace('-','') # 切換目錄 ftp_path=os.path.join('/share/FundFile/',pre_day) ftp.cwd(ftp_path) file_list = ftp.nlst() data = [ name for name in file_list ] def download(ftp,filename): print(filename) with open(filename,'wb+') as fp: try: ftp.retrbinary("RETR%s"%filename,fp.write,CONST_BUFFER_SIZE) fp.flush() except : return False return True data_path=os.path.join('/tmp',cur_day.replace('-','')) if not os.path.exists(data_path): os.makedirs(data_path) os.chdir(data_path) for f in data: download(ftp,f) print(data) #f = open(data_path) print('success') logger.info("結束執行.")
異常問題
報錯:ftp.retrbinary No such file or directory
ftp.retrbinary("RETR%s"%filename,fp.write,CONST_BUFFER_SIZE)
RETR與%s之間不能有空格。這問題好像是隻出現在Serve-U 的FTP。linux下做的FTP沒這問題。