From e9e00eb436dd5371c35101d40c0fd2f72ad4500d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Volkan=20=C5=9Eahin?= Date: Wed, 21 Sep 2016 11:21:43 +0300 Subject: [PATCH] mail client added, some features added to plugin script --- .../{commander.py => command_manager.py} | 0 opt/ahenk/base/logging/AhenkLogger.py | 34 ---------- opt/ahenk/base/mail/mail_manager.py | 68 +++++++++++++++++++ .../base/plugin/{Plugin.py => plugin.py} | 51 +++++++++----- 4 files changed, 101 insertions(+), 52 deletions(-) rename opt/ahenk/base/command/{commander.py => command_manager.py} (100%) delete mode 100644 opt/ahenk/base/logging/AhenkLogger.py create mode 100644 opt/ahenk/base/mail/mail_manager.py rename opt/ahenk/base/plugin/{Plugin.py => plugin.py} (83%) diff --git a/opt/ahenk/base/command/commander.py b/opt/ahenk/base/command/command_manager.py similarity index 100% rename from opt/ahenk/base/command/commander.py rename to opt/ahenk/base/command/command_manager.py diff --git a/opt/ahenk/base/logging/AhenkLogger.py b/opt/ahenk/base/logging/AhenkLogger.py deleted file mode 100644 index 33d9f4e..0000000 --- a/opt/ahenk/base/logging/AhenkLogger.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Author: İsmail BAŞARAN -import logging -import logging.config - -from base.scope import Scope - - -class AAAAAAAhenkLogger(object): - """docstring for Logger""" - - def __init__(self): - super(Logger, self).__init__() - scope = Scope.getInstance() - configManager = scope.getConfigurationManager() - - logging.config.fileConfig(configManager.get('BASE', 'logConfigurationFilePath')) - self.logger = logging.getLogger() - - def getLogger(self): - return self.logger - - def info(self, logstring): - self.logger.info(logstring) - - def warning(self, logstring): - self.logger.warning(logstring) - - def error(self, logstring): - self.logger.error(logstring) - - def debug(self, logstring): - self.logger.debug(logstring) diff --git a/opt/ahenk/base/mail/mail_manager.py b/opt/ahenk/base/mail/mail_manager.py new file mode 100644 index 0000000..60ad6dd --- /dev/null +++ b/opt/ahenk/base/mail/mail_manager.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Author: Volkan Şahin + +import smtplib +import os +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.base import MIMEBase +from email.utils import formatdate +from email import encoders +from base.scope import Scope + + +class Mail: + def __init__(self): + scope = Scope().get_instance() + self.logger = scope.get_logger() + self.configuration_manager = scope.get_configuration_manager() + try: + self.smtp_host = self.configuration_manager.get('MAIL', 'smtp_host') + self.smtp_port = int(self.configuration_manager.get('MAIL', 'smtp_port')) + self.from_username = self.configuration_manager.get('MAIL', 'from_username') + self.from_password = self.configuration_manager.get('MAIL', 'from_password') + self.to_address = self.configuration_manager.get('MAIL', 'to_address') + + except Exception as e: + self.logger.error( + 'A problem occurred while reading mail server parameters from conf file. Error Message: {0}'.format( + e)) + self.server = None + self.logger.debug('Mail service initialized.') + + def connect(self): + self.logger.debug('Connecting to SMTP server') + self.server = smtplib.SMTP(self.smtp_host, self.smtp_port) + self.logger.debug('Setting debug level') + self.server.set_debuglevel(2) + self.logger.debug('Using tls if server supports') + self.server.starttls() + self.logger.debug('Loging in to smtp server as {0}'.format(self.from_username)) + self.server.login(self.from_username, self.from_password) + + def disconnect(self): + self.logger.debug('Disconnecting from mail server') + self.server.quit() + self.logger.debug('Disconnected') + + def send_mail(self, subject, message, files=[]): + + msg = MIMEMultipart() + msg['Date'] = formatdate(localtime=True) + msg['Subject'] = subject + + msg.attach(MIMEText(message)) + + #TODO files attachment max size + if files is not None: + for f in files: + part = MIMEBase('application', "octet-stream") + part.set_payload(open(f, "rb").read()) + encoders.encode_base64(part) + part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f))) + msg.attach(part) + + self.logger.debug('Sending mail to {0} {1}'.format(self.to_address, ' about {0}'.format(subject))) + self.server.sendmail(self.from_username, self.to_address, msg.as_string()) + self.logger.debug('Mail was sent.') diff --git a/opt/ahenk/base/plugin/Plugin.py b/opt/ahenk/base/plugin/plugin.py similarity index 83% rename from opt/ahenk/base/plugin/Plugin.py rename to opt/ahenk/base/plugin/plugin.py index 66ebcc6..cd5c658 100644 --- a/opt/ahenk/base/plugin/Plugin.py +++ b/opt/ahenk/base/plugin/plugin.py @@ -6,12 +6,12 @@ import json import threading -from base.scope import Scope from base.file.file_transfer_manager import FileTransferManager -from base.model.response import Response from base.model.enum.content_type import ContentType from base.model.enum.message_code import MessageCode from base.model.enum.message_type import MessageType +from base.model.response import Response +from base.scope import Scope from base.system.system import System from base.util.util import Util @@ -19,7 +19,7 @@ from base.util.util import Util class Context(object): def __init__(self): self.data = dict() - self.scope = Scope().getInstance() + self.scope = Scope().get_instance() def put(self, var_name, data): self.data[var_name] = data @@ -39,6 +39,13 @@ class Context(object): self.data['responseData'] = data self.data['contentType'] = content_type + def fetch_file(self, local_path=None): + file_manager = FileTransferManager(self.get('protocol'), self.get('parameter_map')) + file_manager.transporter.connect() + success = file_manager.transporter.get_file(local_path) + file_manager.transporter.disconnect() + return success + class Plugin(threading.Thread): """ @@ -51,11 +58,11 @@ class Plugin(threading.Thread): self.name = name self.InQueue = InQueue - scope = Scope.getInstance() - self.logger = scope.getLogger() - self.response_queue = scope.getResponseQueue() - self.messaging = scope.getMessageManager() - self.db_service = scope.getDbService() + scope = Scope.get_instance() + self.logger = scope.get_logger() + self.response_queue = scope.get_response_queue() + self.messaging = scope.get_message_manager() + self.db_service = scope.get_db_service() self.keep_run = True self.context = Context() @@ -73,10 +80,14 @@ class Plugin(threading.Thread): if obj_name == "TASK": self.logger.debug('[Plugin] Executing task') - command = Scope.getInstance().getPluginManager().find_command(self.getName(), - item_obj.get_command_cls_id().lower()) + command = Scope.get_instance().get_plugin_manager().find_command(self.getName(), + item_obj.get_command_cls_id().lower()) self.context.put('task_id', item_obj.get_id()) + if item_obj.get_file_server() is not None and item_obj.get_file_server() != 'null': + self.context.put('protocol', json.loads(item_obj.get_file_server())['protocol']) + self.context.put('parameterMap', json.loads(item_obj.get_file_server())['parameterMap']) + task_data = item_obj.get_parameter_map() self.logger.debug('[Plugin] Sending notify to user about task process') @@ -121,14 +132,14 @@ class Plugin(threading.Thread): if success is False: response = Response(type=MessageType.TASK_STATUS.value, id=item_obj.get_id(), code=MessageCode.TASK_ERROR.value, - message='[Ahenk Core] Task processed successfully but file transfer not completed. Check defined server conf') + message='Task processed successfully but file transfer not completed. Check defined server conf') message = self.messaging.task_status_msg(response) - Scope.getInstance().getMessenger().send_direct_message(message) + Scope.get_instance().get_messenger().send_direct_message(message) else: self.logger.debug('[Plugin] Sending task response') - Scope.getInstance().getMessenger().send_direct_message( + Scope.get_instance().get_messenger().send_direct_message( self.messaging.task_status_msg(response)) else: @@ -139,7 +150,7 @@ class Plugin(threading.Thread): self.logger.debug('[Plugin] Executing profile') profile_data = item_obj.get_profile_data() - policy_module = Scope.getInstance().getPluginManager().find_policy_module( + policy_module = Scope.get_instance().get_plugin_manager().find_policy_module( item_obj.get_plugin().get_name()) self.context.put('username', item_obj.get_username()) @@ -149,6 +160,10 @@ class Plugin(threading.Thread): self.context.put('policy_version', policy_ver) self.context.put('execution_id', execution_id) + # if item_obj.get_file_server() is not None and item_obj.get_file_server() !='null': + # self.context.put('protocol', json.loads(item_obj.get_file_server())['protocol']) + # self.context.put('parameterMap', json.loads(item_obj.get_file_server())['parameterMap']) + self.logger.debug('[Plugin] Sending notify to user about profile process') Util.send_notify("Lider Ahenk", @@ -189,18 +204,18 @@ class Plugin(threading.Thread): if success is False: response = Response(type=MessageType.POLICY_STATUS.value, id=item_obj.get_id(), code=MessageCode.POLICY_ERROR.value, - message='[Ahenk Core] Policy processed successfully but file transfer not completed. Check defined server conf') + message='Policy processed successfully but file transfer not completed. Check defined server conf') message = self.messaging.task_status_msg(response) - Scope.getInstance().getMessenger().send_direct_message(message) + Scope.get_instance().get_messenger().send_direct_message(message) else: self.logger.debug('[Plugin] Sending profile response') - Scope.getInstance().getMessenger().send_direct_message( + Scope.get_instance().get_messenger().send_direct_message( self.messaging.policy_status_msg(response)) else: self.logger.error( '[Plugin] There is no Response. Plugin must create response after run a policy!') elif 'MODE' in obj_name: - module = Scope.getInstance().getPluginManager().find_module(obj_name, self.name) + module = Scope.get_instance().get_plugin_manager().find_module(obj_name, self.name) if module is not None: if item_obj.obj_name in ('LOGIN_MODE', 'LOGOUT_MODE', 'SAFE_MODE'): self.context.put('username', item_obj.username)