示例#1
0
 def job(self, args):
     task, node, results = args
     dict_result = {}
     try:
         driver = get_network_driver(node.operating_system)
         napalm_driver = driver(
             hostname=node.ip_address,
             username=task.user.name,
             password=cisco_type7.decode(task.user.password),
             optional_args={'secret': node.secret_password}
         )
         napalm_driver.open()
         for getter in self.getters:
             try:
                 dict_result[getter] = str_dict(getattr(napalm_driver, getter)())
             except Exception as e:
                 dict_result[getter] = '{} could not be retrieve because of {}'.format(getter, e)
         napalm_driver.close()
     except Exception as e:
         dict_result['error'] = 'getters process did not work because of {}'.format(e)
         success = False
     else:
         success = True
     result = dict_result
     results[node.name] = {'success': success, 'logs': result}
示例#2
0
    def job(self, args):
        task, node, results = args
        success, outputs = True, {}
        try:
            netmiko_handler = ConnectHandler(
                device_type=self.driver,
                ip=node.ip_address,
                username=task.user.name,
                password=cisco_type7.decode(task.user.password),
                secret=node.secret_password
            )
            for i in range(1, 4):
                command = getattr(self, 'command' + str(i))
                if not command:
                    continue
                output = netmiko_handler.send_command(command)
                pattern = getattr(self, 'pattern' + str(i))
                result = 'Output: {}\n\nExpected pattern: {}'.format(output, pattern)
                outputs[command] = result
                if pattern not in output:
                    success = False

        except Exception as e:
            results[node.name] = 'netmiko did not work because of {}'.format(e)
            success = False
        result = str_dict(outputs)
        try:
            netmiko_handler.disconnect()
        except Exception:
            pass
        results[node.name] = {'success': success, 'logs': result}
示例#3
0
def scheduler_job(job_id, aps_job_id=None, targets=None):
    with scheduler.app.app_context():
        job = fetch('Job', id=job_id)
        if targets:
            targets = [
                fetch('Device', id=device_id)
                for device_id in targets
            ]
        results, now = job.try_run(targets=targets)
        task = fetch('Task', creation_time=aps_job_id)
        if task and not task.frequency:
            task.status = 'Completed'
        parameters = get_one('Parameters')
        if job.push_to_git and parameters.git_repository_automation:
            path_git_folder = Path.cwd() / 'git' / 'automation'
            with open(path_git_folder / job.name, 'w') as file:
                file.write(str_dict(results))
            repo = Repo(str(path_git_folder))
            try:
                repo.git.add(A=True)
                repo.git.commit(m=f'Automatic commit ({job.name})')
            except GitCommandError:
                pass
            repo.remotes.origin.push()
        db.session.commit()
 def slack_feedback_notification(self, payload):
     parameters = get_one('Parameters')
     slack_client = SlackClient(parameters.slack_token)
     result = slack_client.api_call('chat.postMessage',
                                    channel=parameters.slack_channel,
                                    text=str_dict(payload['result']))
     return {'success': True, 'result': str(result)}
示例#5
0
 def slack_feedback_notification(self, payload: dict) -> dict:
     parameters = get_one("Parameters")
     slack_client = SlackClient(parameters.slack_token)
     result = slack_client.api_call(
         "chat.postMessage",
         channel=parameters.slack_channel,
         text=str_dict(payload["result"]),
     )
     return {"success": True, "result": str(result)}
示例#6
0
 def job(self, task, device, results, payloads):
     result = {}
     results['expected'] = self.content_match
     try:
         napalm_driver = napalm_connection(device)
         napalm_driver.open()
         for getter in self.getters:
             try:
                 result[getter] = getattr(napalm_driver, getter)()
             except Exception as e:
                 result[getter] = f'{getter} failed because of {e}'
         if self.content_match_regex:
             success = bool(search(self.content_match, str_dict(result)))
         else:
             success = self.content_match in str_dict(result)
         napalm_driver.close()
     except Exception as e:
         result = f'script did not work:\n{e}'
         success = False
     return success, result, result
示例#7
0
 def mail_feedback_notification(self, payload):
     parameters = get_one('Parameters')
     message = Message(payload['job']['name'],
                       sender=parameters.mail_sender,
                       recipients=parameters.mail_recipients.split(','),
                       body=payload['result'])
     runtime = payload["runtime"].replace('.', '').replace(':', '')
     filename = f'logs-{runtime}.txt'
     with open(filename, 'w') as file:
         file.write(str_dict(payload["logs"][payload["runtime"]]))
     with open(filename, 'r') as file:
         message.attach(filename, 'text/plain', file.read())
     remove(filename)
     mail.send(message)
     return {'success': True}
示例#8
0
 def mail_feedback_notification(self, payload: dict) -> dict:
     parameters = get_one("Parameters")
     name, recipients = (
         payload["job"]["name"],
         (payload["job"]["mail_recipient"].split(",")
          or parameters.mail_recipients.split(",")),
     )
     message = Message(
         name,
         sender=parameters.mail_sender,
         recipients=recipients,
         body=payload["result"],
     )
     runtime = payload["runtime"].replace(".", "").replace(":", "")
     filename = f"logs-{name}-{runtime}.txt"
     with open(filename, "w") as file:
         file.write(str_dict(payload["logs"][payload["runtime"]]))
     with open(filename, "r") as file:
         message.attach(filename, "text/plain", file.read())
     remove(filename)
     mail_client.send(message)
     return {"success": True}
示例#9
0
文件: helpers.py 项目: fublu/eNMS
def scheduler_job(job_id: int,
                  aps_job_id: Optional[str] = None,
                  targets: Optional[Set[Device]] = None) -> None:
    with scheduler.app.app_context():
        task = fetch("Task", creation_time=aps_job_id)
        job = fetch("Job", id=job_id)
        if targets:
            targets = {fetch("Device", id=device_id) for device_id in targets}
        results, now = job.try_run(targets=targets)
        parameters = get_one("Parameters")
        if job.push_to_git and parameters.git_automation:
            path_git_folder = Path.cwd() / "git" / "automation"
            with open(path_git_folder / job.name, "w") as file:
                file.write(str_dict(results))
            repo = Repo(str(path_git_folder))
            try:
                repo.git.add(A=True)
                repo.git.commit(m=f"Automatic commit ({job.name})")
            except GitCommandError:
                pass
            repo.remotes.origin.push()
        if task and not task.frequency:
            task.is_active = False
        db.session.commit()
示例#10
0
文件: routes.py 项目: usafak/eNMS
def get_diff(job_id, v1, v2, n1=None, n2=None):
    job = fetch('Job', id=job_id)
    first = str_dict(job.logs[v1]).splitlines()
    second = str_dict(job.logs[v2]).splitlines()
    opcodes = SequenceMatcher(None, first, second).get_opcodes()
    return {'first': first, 'second': second, 'opcodes': opcodes}
示例#11
0
def get_diff(task_id, v1, v2, n1, n2):
    task = retrieve(Task, id=task_id)
    first = str_dict(task.logs[v1]['logs'][n1]).splitlines()
    second = str_dict(task.logs[v2]['logs'][n2]).splitlines()
    opcodes = SequenceMatcher(None, first, second).get_opcodes()
    return jsonify({'first': first, 'second': second, 'opcodes': opcodes})
示例#12
0
def show_logs(task_id):
    return jsonify(str_dict(retrieve(Task, id=task_id).logs))
示例#13
0
def show_logs(task_id):
    task = get_obj(Task, id=task_id)
    return jsonify(str_dict(task.logs))
示例#14
0
def get_diff(job_id: int, v1: str, v2: str) -> dict:
    job = fetch("Job", id=job_id)
    first = str_dict(job.logs[v1]).splitlines()
    second = str_dict(job.logs[v2]).splitlines()
    opcodes = SequenceMatcher(None, first, second).get_opcodes()
    return {"first": first, "second": second, "opcodes": opcodes}