1 # _*_ coding:utf-8 _*_ 2 3 """ 4 __title__ = 'download ftp xml data' 5 __author__ = 'Lucky' 6 __date__ = '2018/07/06 7 """ 8 9 import ftplib 10 import time 11 12 class Ftp_download: 13 14 def __init__(self,host,username,password,str_time,file,port=21,bufsize=1024): 15 self.ftp = ftplib.FTP() 16 self.host = host 17 self.username = username 18 self.password = password 19 self.str_time = str_time 20 self.file = file 21 self.port = port 22 self.bufsize = bufsize 23 24 def ftp_download(self): 25 self.ftp.connect(self.host, self.port,timeout=20) 26 self.ftp.login(self.username,self.password) 27 28 file_local_dir = '/home/tmp/test/' + self.file 29 data_file = self.ftp.nlst() 30 31 count = 0 32 while count < 4: 33 if self.file in data_file: 34 fp = open(file_local_dir, 'wb') 35 self.ftp.retrbinary('RETR %s' % self.file, fp.write, self.bufsize) 36 return True 37 else: 38 time.sleep(500) 39 count += 1 40 continue 41 return False 42 43 def logout(self): 44 self.ftp.close() 45 46 def main(): 47 48 str_time = time.strftime("%Y%m%d", time.localtime()) 49 file = str_time + ".tar" + ".gz" 50 51 new_ftp = Ftp_download('192.168.2.3', 'testuser', 'testpasswd', str_time, file) # 傳遞ftp用戶名密碼時間和文件名 52 53 if new_ftp.ftp_download(): 54 new_ftp.logout() 55 else: 56 new_ftp.logout() 57 58 if __name__ == "__main__": 59 main()