How to use the napalm.base function in napalm

To help you get started, we’ve selected a few napalm examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github napalm-automation / napalm / test / base / test_mock_driver.py View on Github external
def test_basic(self):
        d = driver("blah", "bleh", "blih", optional_args=optional_args)
        assert d.is_alive() == {"is_alive": False}
        d.open()
        assert d.is_alive() == {"is_alive": True}
        d.close()
        assert d.is_alive() == {"is_alive": False}

        with pytest.raises(napalm.base.exceptions.ConnectionClosedException) as excinfo:
            d.get_facts()
        assert "connection closed" in str(excinfo.value)
github napalm-automation / napalm / test / base / test_mock_driver.py View on Github external
def test_context_manager(self):
        with pytest.raises(napalm.base.exceptions.ConnectionException) as e, driver(
            "blah", "bleh", "blih", optional_args=fail_args
        ) as d:
            pass
        assert "You told me to do this" in str(e.value)
        with pytest.raises(AttributeError) as e, driver(
            "blah", "bleh", "blih", optional_args=optional_args
        ) as d:
            assert d.is_alive() == {"is_alive": True}
            d.__fake_call()
        assert d.is_alive() == {"is_alive": False}
        assert "object has no attribute" in str(e.value)
github napalm-automation-community / napalm-ce / napalm_ce / ce.py View on Github external
match_proto = re.search(re_protocol, interface, flags=re.M)

            if match_intf is None or match_proto is None:
                msg = "Unexpected interface format: {}".format(interface)
                raise ValueError(msg)
            intf_name = match_intf.group('intf_name')
            intf_state = match_intf.group('intf_state')
            is_enabled = bool('up' in intf_state.lower())

            protocol = match_proto.group('protocol')
            is_up = bool('up' in protocol.lower())

            match_mac = re.search(re_mac, interface, flags=re.M)
            if match_mac:
                mac_address = match_mac.group('mac_address')
                mac_address = napalm.base.helpers.mac(mac_address)
            else:
                mac_address = ""

            speed = -1
            match_speed = re.search(re_speed, interface, flags=re.M)
            if match_speed:
                speed = match_speed.group('speed')
                if speed.isdigit():
                    speed = int(speed)

            description = ''
            match = re.search(re_description, interface, flags=re.M)
            if match:
                description = match.group('description')

            interfaces.update({
github napalm-automation-community / napalm-ce / napalm_ce / ce.py View on Github external
"""
        arp_table = []
        output = self.device.send_command('display arp')
        re_arp = r"(?P\d+\.\d+\.\d+\.\d+)\s+(?P\S+)\s+(?P\d+|)\s+" \
                 r"(?PI|D|S|O)\s+(?P\S+)"
        match = re.findall(re_arp, output, flags=re.M)

        for arp in match:
            # if arp[2].isdigit():
            #     exp = float(arp[2]) * 60
            # else:
            #     exp = 0

            entry = {
                'interface': arp[4],
                'mac': napalm.base.helpers.mac(arp[1]),
                'ip': arp[0],
                'age': -1.0,
            }
            arp_table.append(entry)
        return arp_table
github napalm-automation / napalm / napalm / base / base.py View on Github external
"""
        Will load a templated configuration on the device.

        :param cls: Instance of the driver class.
        :param template_name: Identifies the template name.
        :param template_source (optional): Custom config template rendered and loaded on device
        :param template_path (optional): Absolute path to directory for the configuration templates
        :param template_vars: Dictionary with arguments to be used when the template is rendered.
        :raise DriverTemplateNotImplemented: No template defined for the device type.
        :raise TemplateNotImplemented: The template specified in template_name does not exist in \
        the default path or in the custom path if any specified using parameter `template_path`.
        :raise TemplateRenderException: The template could not be rendered. Either the template \
        source does not have the right format, either the arguments in `template_vars` are not \
        properly specified.
        """
        return napalm.base.helpers.load_template(
            self,
            template_name,
            template_source=template_source,
            template_path=template_path,
            **template_vars
        )
github napalm-automation / napalm / napalm / junos / junos.py View on Github external
key: self._parse_value(value)
                    for key, value in neighbor_details.items()
                    if key in keys
                }
                peer["local_as"] = napalm.base.helpers.as_number(peer["local_as"])
                peer["remote_as"] = napalm.base.helpers.as_number(peer["remote_as"])
                peer["address_family"] = self._parse_route_stats(
                    neighbor_details, instance
                )
                if "peers" not in bgp_neighbor_data[instance_name]:
                    bgp_neighbor_data[instance_name]["peers"] = {}
                bgp_neighbor_data[instance_name]["peers"][peer_ip] = peer
                if not uptime_table_items:
                    uptime_table_items = _get_uptime_table(instance)
                for neighbor, uptime in uptime_table_items:
                    normalized_neighbor = napalm.base.helpers.ip(neighbor)
                    if (
                        normalized_neighbor
                        not in bgp_neighbor_data[instance_name]["peers"]
                    ):
                        bgp_neighbor_data[instance_name]["peers"][
                            normalized_neighbor
                        ] = {}
                    bgp_neighbor_data[instance_name]["peers"][normalized_neighbor][
                        "uptime"
                    ] = uptime[0][1]
github napalm-automation / napalm / napalm / ios / ios.py View on Github external
"""Return proper data for mac address fields."""
            if mac_type.lower() in ["self", "static", "system"]:
                static = True
                if vlan.lower() == "all":
                    vlan = 0
                if (
                    interface.lower() == "cpu"
                    or re.search(r"router", interface.lower())
                    or re.search(r"switch", interface.lower())
                ):
                    interface = ""
            else:
                static = False

            return {
                "mac": napalm.base.helpers.mac(mac),
                "interface": self._canonical_int(interface),
                "vlan": int(vlan),
                "static": static,
                "active": True,
                "moves": -1,
                "last_move": -1.0,
            }
github napalm-automation / napalm / napalm / eos / eos.py View on Github external
hop_regex = "".join(_HOP_ENTRY + _HOP_ENTRY_PROBE * probes)

        traceroute_result["success"] = {}
        for line in traceroute_raw_output.splitlines():
            hop_search = re.search(hop_regex, line)
            if not hop_search:
                continue
            hop_details = hop_search.groups()
            hop_index = int(hop_details[0])
            previous_probe_host_name = "*"
            previous_probe_ip_address = "*"
            traceroute_result["success"][hop_index] = {"probes": {}}
            for probe_index in range(probes):
                host_name = hop_details[3 + probe_index * 5]
                hop_addr = hop_details[4 + probe_index * 5]
                ip_address = napalm.base.helpers.convert(
                    napalm.base.helpers.ip, hop_addr, hop_addr
                )
                rtt = hop_details[5 + probe_index * 5]
                if rtt:
                    rtt = float(rtt)
                else:
                    rtt = timeout * 1000.0
                if not host_name:
                    host_name = previous_probe_host_name
                if not ip_address:
                    ip_address = previous_probe_ip_address
                if hop_details[1 + probe_index * 5] == "*":
                    host_name = "*"
                    ip_address = "*"
                traceroute_result["success"][hop_index]["probes"][probe_index + 1] = {
                    "host_name": str(host_name),
github napalm-automation / napalm / napalm / ros / ros.py View on Github external
def get_facts(self):
        resource = self.api('/system/resource/print')[0]
        identity = self.api('/system/identity/print')[0]
        routerboard = self.api('/system/routerboard/print')[0]
        interfaces = self.api('/interface/print')
        return {
            'uptime': to_seconds(resource['uptime']),
            'vendor': resource['platform'],
            'model': resource['board-name'],
            'hostname': identity['name'],
            'fqdn': u'',
            'os_version': resource['version'],
            'serial_number': routerboard.get('serial-number', ''),
            'interface_list': napalm.base.utils.string_parsers.sorted_nicely(
                tuple(iface['name'] for iface in interfaces)
            ),