예제 #1
0
 def safe_ncs_decrypt(value):
     if value is None:
         return None
     try:
         return _ncs.decrypt(len=255, ciphertext=value)
     except:
         return _ncs.decrypt(ciphertext=value)
예제 #2
0
    def check_connectivity(self, service, link, root, action_output):
        host_data = {
            'protocol': 'ssh',
            'os': 'ios',
        }
        host_data['ip'] = root.devices.device[link.ce.device].address

        auth = root.devices.authgroups.group['labadmin'].default_map
        host_data['username'] = auth.remote_name
        host_data['password'] = decrypt(auth.remote_password)

        test_setup = genie.testbed.load({'devices': {'host': host_data}})
        host = test_setup.devices['host']
        host.connect(learn_hostname=True)

        action_output.output = ''
        action_output.success = True

        this_link = link.link_name
        for l in service.link:
            if l.link_name == this_link:
                continue

            action_output.output += f'\n{l.link_name} '
            try:
                host.ping(l.ce.ip)
                action_output.output += 'PASS'
            except:
                action_output.output += 'FAIL'
                action_output.success = False

        host.disconnect()
예제 #3
0
def getVNFPasswords(log, root, device):
    authgroup = root.devices.authgroups.group[device.authgroup]
    username = authgroup.default_map.remote_name
    password = _ncs.decrypt(authgroup.default_map.remote_password)
    auths = (authgroup.name, username, password)
    log.info('VNF auths: {}'.format(auths))
    return auths
예제 #4
0
    def cb_action(self, uinfo, name, kp, input, output):
        self.log.info("Action {}".format(kp))

        with ncs.maapi.single_read_trans(uinfo.username, "system") as read_t:
            root = ncs.maagic.get_root(read_t)

            rest_params = root.ncs__services.vnf_deploy__vnf_deploy.rest_callback
            uri = rest_params.uri
            source_data = rest_params.payload
            rest_user = rest_params.username
            read_t.maapi.install_crypto_keys()
            rest_pass = decrypt(rest_params.password)

            # kp example: /ncs:services/vnf-deploy:vnf-deploy/vnf{csr-123}
            kp_node = ncs.maagic.cd(root, kp)
            data_vars = {
                'vnf_name': kp_node.name,
            }

        # Process source_data through Jinja2
        jinja_env = jinja2.Environment(autoescape=True, trim_blocks=True, lstrip_blocks=True)
        data = jinja_env.from_string(source_data).render(data_vars)

        # Send REST notification
        try:
            response = requests.post(url=uri, auth=(rest_user, rest_pass), data=data)
            response.raise_for_status()
            self.log.info("REST notification sent successfully: status code {}.".format(response.status_code))
        except requests.exceptions.RequestException as e:
            self.log.error("REST notification failed: {}".format(e))
예제 #5
0
def vmlist_netbox(netbox_inventory, netbox_server, log=False):
    """Retrieve matching Virtual Machines from NetBox for an inventory"""

    try:
        nb = pynetbox.api(netbox_server.url,
                          token=decrypt(netbox_server.api_token))

        # Build the VM query from the provided attributes to the inventory instance
        vm_query = {}
        if netbox_inventory.site:
            if log:
                log.info("Looking up NetBox Sites to Filter.")
            sites = query_netbox(nb.dcim.sites,
                                 log,
                                 name=[site for site in netbox_inventory.site])
            vm_query["site_id"] = [site.id for site in sites]

        if netbox_inventory.tenant:
            if log:
                log.info("Looking up NetBox Tenants to Filter.")
            tenants = query_netbox(
                object=nb.tenancy.tenants,
                log=log,
                name=[tenant for tenant in netbox_inventory.tenant],
            )
            vm_query["tenant_id"] = [tenant.id for tenant in tenants]

        if netbox_inventory.vm_role:
            if log:
                log.info("Looking up NetBox Virtual Machine Roles to Filter.")
            vm_roles = query_netbox(
                object=nb.dcim.device_roles,
                log=log,
                name=[vm_role.role for vm_role in netbox_inventory.vm_role],
                vm_role=True,
            )
            vm_query["role_id"] = [vm_role.id for vm_role in vm_roles]

        if log:
            log.info(f"Looking up NetBox vms for Filter: {vm_query}")
        vms = query_netbox(object=nb.virtualization.virtual_machines,
                           log=log,
                           **vm_query)

        return {"status": True, "result": vms}
    except Exception as e:
        if log:
            log.error(f"Lookup failed: {e}")
        return {"status": False, "result": e}
예제 #6
0
 def get_authgroup_info(self, trans: Transaction, root: Node, locuser: str, authmap: Node) \
         -> Tuple[Optional[str], Optional[str]]:
     if authmap.same_user.exists():
         username = locuser
     else:
         username = authmap.remote_name
     if username is None:
         return None, None
     if authmap.same_pass.exists():
         upwd = root.aaa.authentication.users.user[locuser].password
     else:
         upwd = authmap.remote_password
     if upwd is None:
         return username, None
     trans.maapi.install_crypto_keys()
     return username, _ncs.decrypt(upwd)
예제 #7
0
        def send_rest_notification(**kwargs):
            # Retrieve configured REST parameters
            with ncs.maapi.single_read_trans(uinfo.username, "system") as read_t:
                rest_params = ncs.maagic.get_node(read_t, kp).rest
                uri = rest_params.uri
                source_data = rest_params.payload
                rest_user = rest_params.username
                read_t.maapi.install_crypto_keys()
                rest_pass = _ncs.decrypt(rest_params.password)

            # Process source_data through jinja2
            jinja_env = jinja2.Environment(autoescape=True, trim_blocks=True, lstrip_blocks=True)
            data = jinja_env.from_string(source_data).render(kwargs)

            # Send REST notification
            try:
                response = requests.post(url=uri, auth=(rest_user, rest_pass), data=data)
                response.raise_for_status()
                self.log.info("REST notification sent successfully: status code {}.".format(response.status_code))
            except requests.exceptions.RequestException as e:
                self.log.error("REST notification failed: {}".format(e))
예제 #8
0
def verify_netbox(netbox_server):
    """Verify a NetBox Server is reachable"""
    nb = pynetbox.api(netbox_server.url,
                      token=decrypt(netbox_server.api_token))
    try:
        status = nb.status()
    except RequestError as e:
        # Older versions of NetBox don't have the status api, try to retrieve devices
        devices = nb.dcim.devices.all()
        return {
            "status": True,
            "message": f"Successfully connected to NetBox to query devices."
        }
    except exceptions.ConnectionError:
        return {
            "status":
            False,
            "message":
            f"Error connecting to NetBox Server at url {netbox_server.url}.",
        }

    status_message = f"NetBox Version: {status['netbox-version']}, Python Version: {status['python-version']}, Plugins: {status['plugins']}, Workers Running: {status['rq-workers-running']}"
    return {"status": True, "message": status_message}
예제 #9
0
 def cb_action(self, uinfo, name, kp, action_input, action_output, t):
     maapi = ncs.maapi.Maapi()
     maapi.install_crypto_keys()
     pycnt = ncs.maagic.get_node(t, kp)
     cleartext = _ncs.decrypt(pycnt.encrypted_value)
     action_output.message = f"cleartext: {cleartext}"
예제 #10
0
def decrypt(value):
    with maapi.Maapi() as m:
        m.install_crypto_keys()
    return _ncs.decrypt(value)
예제 #11
0
def devicelist_netbox(netbox_inventory, netbox_server, log=False):
    """Retrieve matching devices from NetBox for an inventory"""

    try:
        nb = pynetbox.api(netbox_server.url,
                          token=decrypt(netbox_server.api_token))

        # Build the device query from the provided attributes to the inventory instance
        device_query = {}
        if netbox_inventory.site:
            if log:
                log.info("Looking up NetBox Sites to Filter.")
            sites = query_netbox(nb.dcim.sites,
                                 log,
                                 name=[site for site in netbox_inventory.site])
            device_query["site_id"] = [site.id for site in sites]

        if netbox_inventory.tenant:
            if log:
                log.info("Looking up NetBox Tenants to Filter.")
            tenants = query_netbox(
                object=nb.tenancy.tenants,
                log=log,
                name=[tenant for tenant in netbox_inventory.tenant],
            )
            device_query["tenant_id"] = [tenant.id for tenant in tenants]

        if netbox_inventory.device_type:
            if log:
                log.info("Looking up NetBox Device-Types to Filter.")
            device_types = query_netbox(
                object=nb.dcim.device_types,
                log=log,
                model=[
                    device_type.model
                    for device_type in netbox_inventory.device_type
                ],
            )
            device_query["device_type_id"] = [
                device_type.id for device_type in device_types
            ]

        if netbox_inventory.device_role:
            if log:
                log.info("Looking up NetBox Device-Roles to Filter.")
            device_roles = query_netbox(
                object=nb.dcim.device_roles,
                log=log,
                name=[
                    device_role for device_role in netbox_inventory.device_role
                ],
            )
            device_query["role_id"] = [
                device_role.id for device_role in device_roles
            ]

        if log:
            log.info(f"Looking up NetBox Devices for Filter: {device_query}")
        devices = query_netbox(object=nb.dcim.devices, log=log, **device_query)

        return {"status": True, "result": devices}
    except Exception as e:
        if log:
            log.error(f"Lookup failed: {e}")
        return {"status": False, "result": e}