from Lib.lcfc_lib import * from Lib.action_base import ActionBase from ftplib import FTP from ftplib import error_perm import socket class ActionFtp(ActionBase): ftp_download_file = 1 # file ftp_upload_file = 2 def __init__(self, **kwargs): super().__init__() self.sub_function = kwargs['sub_function'] self.ftp_ip = kwargs['ftp_ip'] self.ftp_port = kwargs['ftp_port'] self.ftp_account = kwargs['ftp_account'] self.ftp_password = kwargs['ftp_password'] if self.sub_function == ActionFtp.ftp_download_file: self.ftp_file = kwargs['ftp_file'] self.local_file = kwargs['local_file'] elif self.sub_function == ActionFtp.ftp_upload_file: self.local_file = kwargs['local_file'] self.ftp_file = kwargs['ftp_file'] def action(self, count, action_str): super().action(count, action_str) ftp = ftp_connect(self.ftp_ip, self.ftp_port, self.ftp_account, self.ftp_password) if not ftp: self.status = STATUS_ERROR if ftp is not None: ftp.quit() return if self.sub_function == ActionFtp.ftp_download_file: if not self.local_file: self.local_file = self.output_folder self.status = download_file(ftp, self.ftp_file, self.local_file) elif self.sub_function == ActionFtp.ftp_upload_file: self.status = upload_file(ftp, self.ftp_file, self.local_file) if ftp is not None: ftp.quit() return def ftp_connect(host, port, username, password): ftp = FTP() ftp.encoding = 'utf-8' try: ftp.connect(host, port) ftp.login(username, password) # print(ftp.getwelcome()) except(socket.error, socket.gaierror): # ftp connection wrong print("ERROR: cannot connect [{}:{}]" .format(host, port)) return None except error_perm: # user/psw wrong print("ERROR: user Authentication failed ") return None return ftp def download_file(ftp, remote_path, local_path): ret = STATUS_ERROR buf_size = 1024 fp = open(local_path, 'wb') res = ftp.retrbinary('RETR ' + remote_path, fp.write, buf_size) if res.find('226') != -1: # print('Download file complete', local_path) ret = STATUS_SUCCESS ftp.set_debuglevel(0) fp.close() return ret def upload_file(ftp, remote_path, local_path): ret = STATUS_ERROR bufsize = 1024 fp = open(local_path, 'rb') res = ftp.storbinary('STOR ' + remote_path, fp, bufsize) if res.find('226') != -1: # print('upload file complete', remote_path) ret = STATUS_SUCCESS ftp.set_debuglevel(0) fp.close() return ret