Exemplo n.º 1
0
def connection(id):
    parameters, device = get_one('Parameters'), fetch('Device', id=id)
    cmd = [str(app.path / 'applications' / 'gotty'), '-w']
    port, protocol = parameters.get_gotty_port(), request.form['protocol']
    address = getattr(device, request.form['address'])
    cmd.extend(['-p', str(port)])
    if 'accept-once' in request.form:
        cmd.append('--once')
    if 'multiplexing' in request.form:
        cmd.extend(f'tmux new -A -s gotty{port}'.split())
    if app.config['GOTTY_BYPASS_KEY_PROMPT']:
        options = '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
    else:
        options = ''
    if protocol == 'telnet':
        cmd.extend(f'telnet {address}'.split())
    elif 'authentication' in request.form:
        if request.form['credentials'] == 'device':
            login, pwd = device.username, device.password
        else:
            login, pwd = current_user.name, current_user.password
        cmd.extend(f'sshpass -p {pwd} ssh {options} {login}@{address}'.split())
    else:
        cmd.extend(f'ssh {options} {address}'.split())
    if protocol != 'telnet':
        cmd.extend(f'-p {device.port}'.split())
    Popen(cmd)
    return {
        'device': device.name,
        'port': port,
        'redirection': app.config['GOTTY_PORT_REDIRECTION'],
        'server_addr': app.config['ENMS_SERVER_ADDR']
    }
Exemplo n.º 2
0
def connection(id):
    parameters, device = get_one('Parameters'), fetch('Device', id=id)
    cmd = [str(app.path / 'applications' / 'gotty'), '-w']
    port, ip = parameters.get_gotty_port(), device.ip_address
    cmd.extend(['-p', str(port)])
    if 'accept-once' in request.form:
        cmd.append('--once')
    if 'multiplexing' in request.form:
        cmd.extend(f'tmux new -A -s gotty{port}'.split())
    if app.config['GOTTY_BYPASS_KEY_PROMPT']:
        options = '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
    else:
        options = ''
    if 'authentication' in request.form:
        if request.form['credentials'] == 'device':
            login, pwd, _ = get_device_credentials(app, device)
        else:
            login, pwd = get_user_credentials(app, current_user)
        cmd.extend(f'sshpass -p {pwd} ssh {options} {login}@{ip}'.split())
    else:
        cmd.extend(f'ssh {options} {ip}'.split())
    cmd.extend(f'-p {device.port}'.split())
    Popen(cmd)
    return jsonify({
        'device': device.name,
        'port': port,
        'redirection': app.config['GOTTY_PORT_REDIRECTION'],
        'server_addr': app.config['GOTTY_SERVER_ADDR']
    })
Exemplo n.º 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()
Exemplo n.º 4
0
 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)}
Exemplo n.º 5
0
Arquivo: routes.py Projeto: fublu/eNMS
def connection(device_id: int) -> dict:
    parameters, device = get_one("Parameters"), fetch("Device", id=device_id)
    cmd = [str(app.path / "applications" / "gotty"), "-w"]
    port, protocol = parameters.get_gotty_port(), request.form["protocol"]
    address = getattr(device, request.form["address"])
    cmd.extend(["-p", str(port)])
    if "accept-once" in request.form:
        cmd.append("--once")
    if "multiplexing" in request.form:
        cmd.extend(f"tmux new -A -s gotty{port}".split())
    if app.config["GOTTY_BYPASS_KEY_PROMPT"]:
        options = "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
    else:
        options = ""
    if protocol == "telnet":
        cmd.extend(f"telnet {address}".split())
    elif "authentication" in request.form:
        if request.form["credentials"] == "device":
            login, pwd = device.username, device.password
        else:
            login, pwd = current_user.name, current_user.password
        cmd.extend(f"sshpass -p {pwd} ssh {options} {login}@{address}".split())
    else:
        cmd.extend(f"ssh {options} {address}".split())
    if protocol != "telnet":
        cmd.extend(f"-p {device.port}".split())
    Popen(cmd)
    return {
        "device": device.name,
        "port": port,
        "redirection": app.config["GOTTY_PORT_REDIRECTION"],
        "server_addr": app.config["ENMS_SERVER_ADDR"],
    }
Exemplo n.º 6
0
def import_export():
    return render_template(
        'import_export.html',
        import_export_form=ImportExportForm(request.form),
        netbox_form=NetboxForm(request.form),
        opennms_form=OpenNmsForm(request.form),
        parameters=get_one('Parameters'),
    )
Exemplo n.º 7
0
Arquivo: routes.py Projeto: fublu/eNMS
def import_export() -> dict:
    return dict(
        import_export_form=ImportExportForm(request.form),
        librenms_form=LibreNmsForm(request.form),
        netbox_form=NetboxForm(request.form),
        opennms_form=OpenNmsForm(request.form),
        parameters=get_one("Parameters"),
    )
Exemplo n.º 8
0
 def mattermost_feedback_notification(self, payload):
     parameters = get_one('Parameters')
     post(parameters.mattermost_url,
          data=dumps({
              'channel': parameters.mattermost_channel,
              'text': payload['result']
          }))
     return {'success': True}
Exemplo n.º 9
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)}
Exemplo n.º 10
0
def save_parameters():
    parameters = get_one('Parameters')
    remote_git = request.form['git_repository_automation']
    if parameters.git_repository_automation != remote_git:
        Repo.clone_from(remote_git, app.path / 'git' / 'automation')
    parameters.update(**request.form)
    database_filtering(fetch('Pool', id=request.form['pool']))
    db.session.commit()
    return True
Exemplo n.º 11
0
 def cluster_monitoring(self, _):
     parameters = get_one('Parameters')
     protocol = parameters.cluster_scan_protocol
     for instance in fetch_all('Instance'):
         factory(
             'Instance',
             **get(f'{protocol}://{instance.ip_address}/rest/is_alive',
                   timeout=parameters.cluster_scan_timeout).json())
     return {'success': True}
Exemplo n.º 12
0
 def job(self, _):
     parameters = get_one('Parameters')
     slack_client = SlackClient(self.token or parameters.slack_token)
     result = slack_client.api_call(
         'chat.postMessage',
         channel=self.channel or parameters.slack_channel,
         text=self.body
     )
     return {'success': True, 'result': str(result)}
Exemplo n.º 13
0
 def job(self, _) -> dict:
     parameters = get_one("Parameters")
     slack_client = SlackClient(self.token or parameters.slack_token)
     result = slack_client.api_call(
         "chat.postMessage",
         channel=self.channel or parameters.slack_channel,
         text=self.body,
     )
     return {"success": True, "result": str(result)}
Exemplo n.º 14
0
 def job(self, _):
     parameters = get_one('Parameters')
     result = post(parameters.mattermost_url,
                   verify=parameters.mattermost_verify_certificate,
                   data=dumps({
                       "channel": self.channel
                       or parameters.mattermost_channel,
                       "text": self.body
                   }))
     return {'success': True, 'result': str(result)}
Exemplo n.º 15
0
def create_default(app: Flask) -> None:
    create_default_parameters(app)
    parameters = get_one("Parameters")
    create_default_users()
    create_default_pools()
    create_default_services()
    create_default_workflows()
    create_default_tasks(app)
    parameters.trigger_active_parameters(app)
    db.session.commit()
Exemplo n.º 16
0
 def git_push_configurations(self, _):
     parameters = get_one('Parameters')
     if parameters.git_configurations:
         repo = Repo(Path.cwd() / 'git' / 'configurations')
         try:
             repo.git.add(A=True)
             repo.git.commit(m='Automatic commit (configurations)')
         except GitCommandError as e:
             info(f'Git commit failed ({str(e)}')
         repo.remotes.origin.push()
     return {'success': True}
Exemplo n.º 17
0
 def job(self, _) -> dict:
     parameters = get_one("Parameters")
     result = post(
         parameters.mattermost_url,
         verify=parameters.mattermost_verify_certificate,
         data=dumps({
             "channel": self.channel or parameters.mattermost_channel,
             "text": self.body,
         }),
     )
     return {"success": True, "result": str(result)}
Exemplo n.º 18
0
 def git_push_configurations(self, payload: dict) -> dict:
     parameters = get_one("Parameters")
     if parameters.git_configurations:
         repo = Repo(Path.cwd() / "git" / "configurations")
         try:
             repo.git.add(A=True)
             repo.git.commit(m="Automatic commit (configurations)")
         except GitCommandError as e:
             info(f"Git commit failed ({str(e)}")
         repo.remotes.origin.push()
     return {"success": True}
Exemplo n.º 19
0
 def mattermost_feedback_notification(self, payload: dict) -> dict:
     parameters = get_one("Parameters")
     post(
         parameters.mattermost_url,
         verify=parameters.mattermost_verify_certificate,
         data=dumps({
             "channel": parameters.mattermost_channel,
             "text": payload["result"]
         }),
     )
     return {"success": True}
Exemplo n.º 20
0
def configure_poller():
    parameters = get_one('Parameters')
    remote_git = request.form['remote_git_repository']
    if parameters.git_repository_configurations != remote_git:
        Repo.clone_from(remote_git, app.path / 'git' / 'configurations')
        parameters.git_repository_configurations = remote_git
    task = fetch('Task', name='poller_task')
    task.frequency = request.form['polling_frequency']
    db.session.commit()
    task.reschedule()
    return True
Exemplo n.º 21
0
 def git_push_configurations(self, _):
     parameters = get_one('Parameters')
     if parameters.git_repository_configurations:
         repo = Repo(Path.cwd() / 'git' / 'configurations')
         try:
             repo.git.add(A=True)
             repo.git.commit(m='Automatic commit (configurations)')
         except GitCommandError:
             pass
         repo.remotes.origin.push()
     return {'success': True}
Exemplo n.º 22
0
 def job(self, _):
     parameters = get_one('Parameters')
     if self.recipients:
         recipients = self.recipients.split(',')
     else:
         recipients = parameters.mail_sender.split(',')
     message = Message(self.title,
                       sender=self.sender or parameters.mail_sender,
                       recipients=recipients,
                       body=self.body)
     mail.send(message)
     return {'success': True, 'result': str(message)}
Exemplo n.º 23
0
 def compute_pool(self):
     self.devices = list(filter(self.object_match, Device.query.all()))
     self.links = []
     for link in Link.query.all():
         link.__dict__.update({
             'source': link.source,
             'destination': link.destination
         })
         if self.object_match(link):
             self.links.append(link)
     if get_one('Parameters').pool == self:
         database_filtering(self)
Exemplo n.º 24
0
 def cluster_monitoring(self, payload: dict) -> dict:
     parameters = get_one("Parameters")
     protocol = parameters.cluster_scan_protocol
     for instance in fetch_all("Instance"):
         factory(
             "Instance",
             **get(
                 f"{protocol}://{instance.ip_address}/rest/is_alive",
                 timeout=parameters.cluster_scan_timeout,
             ).json(),
         )
     return {"success": True}
Exemplo n.º 25
0
def admninistration():
    database_filtering_form = DatabaseFilteringForm(request.form)
    database_filtering_form.pool.choices = choices('Pool')
    try:
        tacacs_server = get_one('TacacsServer')
    except NoResultFound:
        tacacs_server = None
    try:
        syslog_server = get_one('SyslogServer')
    except NoResultFound:
        syslog_server = None
    return render_template(
        'administration.html',
        database_filtering_form=database_filtering_form,
        geographical_parameters_form=GeographicalParametersForm(request.form),
        gotty_parameters_form=GottyParametersForm(request.form),
        notification_parameters_form=NotificationParametersForm(request.form),
        parameters=get_one('Parameters'),
        tacacs_form=TacacsServerForm(request.form),
        syslog_form=SyslogServerForm(request.form),
        tacacs_server=tacacs_server,
        syslog_server=syslog_server)
Exemplo n.º 26
0
def create_default(app):
    create_default_users()
    create_default_parameters(app)
    parameters = get_one('Parameters')
    parameters.update(**{
        property: app.config[property.upper()]
        for property in parameters_public_properties
        if property.upper() in app.config
    })
    create_default_pools()
    create_default_services()
    create_default_workflows()
    create_default_tasks(app)
    parameters.trigger_active_parameters(app)
Exemplo n.º 27
0
 def job(self, _) -> dict:
     parameters = get_one("Parameters")
     if self.recipients:
         recipients = self.recipients.split(",")
     else:
         recipients = parameters.mail_sender.split(",")
     message = Message(
         self.title,
         sender=self.sender or parameters.mail_sender,
         recipients=recipients,
         body=self.body,
     )
     mail_client.send(message)
     return {"success": True, "result": str(message)}
Exemplo n.º 28
0
def configure_poller():
    parameters = get_one('Parameters')
    remote_git = request.form['remote_git_repository']
    if parameters.git_repository_configurations != remote_git:
        Repo.clone_from(remote_git, app.path / 'git' / 'configurations')
        parameters.git_repository_configurations = remote_git
    service = fetch('Service', name='configuration_backup')
    task = fetch('Task', name='configuration_backup')
    service.devices = objectify('Device', request.form.get('devices', ''))
    service.pools = objectify('Pool', request.form.get('pools', ''))
    task.frequency = request.form['polling_frequency']
    db.session.commit()
    task.reschedule()
    return True
Exemplo n.º 29
0
def view(view_type):
    devices, parameters = fetch_all('Device'), get_one('Parameters').serialized
    return dict(template=f'{view_type}_view.html',
                pools=fetch_all('Pool'),
                parameters=parameters,
                view=request.form.get('view', parameters['default_view']),
                google_earth_form=GoogleEarthForm(request.form),
                add_device_form=AddDevice(request.form),
                add_link_form=AddLink(request.form),
                device_subtypes=device_subtypes,
                link_colors=link_subtype_to_color,
                name_to_id={d.name: id
                            for id, d in enumerate(devices)},
                devices=serialize('Device'),
                links=serialize('Link'))
Exemplo n.º 30
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}