How to use the napalm.base.helpers 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_helpers.py View on Github external
"""
        Tests helper function ```convert```:

            * cast of non-int str to int returns default value
            * cast of str to float returns desired float-type value
            * cast of None obj to string does not cast, but returns default
        """
        self.assertTrue(
            napalm.base.helpers.convert(int, "non-int-value", default=-100) == -100
        )
        # default value returned
        self.assertIsInstance(napalm.base.helpers.convert(float, "1e-17"), float)
        # converts indeed to float
        self.assertFalse(napalm.base.helpers.convert(str, None) == "None")
        # should not convert None-type to 'None' string
        self.assertTrue(napalm.base.helpers.convert(str, None) == "")
        # should return empty unicode
github napalm-automation / napalm / napalm / nxos / nxos.py View on Github external
stupid_cisco_output = stupid_cisco_output.replace("h", "hour(s)")

        things = {
            "second(s)": {"weight": 1},
            "minute(s)": {"weight": 60},
            "hour(s)": {"weight": 3600},
            "day(s)": {"weight": 24 * 3600},
            "week(s)": {"weight": 7 * 24 * 3600},
            "year(s)": {"weight": 365.25 * 24 * 3600},
        }

        things_keys = things.keys()
        for part in stupid_cisco_output.split():
            for key in things_keys:
                if key in part:
                    things[key]["count"] = napalm.base.helpers.convert(
                        int, part.replace(key, ""), 0
                    )

        delta = sum(
            [det.get("count", 0) * det.get("weight") for det in things.values()]
        )
        return time.time() - delta
github napalm-automation / napalm / napalm / ios / ios.py View on Github external
"teardown": {
                                "threshold": prefix_percent,
                                "timeout": prefix_timeout,
                            },
                        }
                    }
                }
            return prefix_limit

        # Get BGP config using ciscoconfparse because some old devices dont support "| sec bgp"
        cfg = self.get_config(retrieve="running")
        cfg = cfg["running"].splitlines()
        bgp_config_text = napalm.base.helpers.cisco_conf_parse_objects(
            "router bgp", cfg
        )
        bgp_asn = napalm.base.helpers.regex_find_txt(
            r"router bgp (\d+)", bgp_config_text, default=0
        )
        # Get a list of all neighbors and groups in the config
        all_neighbors = set()
        all_groups = set()
        bgp_group_neighbors = {}
        all_groups.add("_")
        for line in bgp_config_text:
            if " neighbor " in line:
                if re.search(IP_ADDR_REGEX, line) is not None:
                    all_neighbors.add(re.search(IP_ADDR_REGEX, line).group())
                elif re.search(IPV6_ADDR_REGEX_2, line) is not None:
                    all_neighbors.add(re.search(IPV6_ADDR_REGEX_2, line).group())
                else:
                    bgp_group = re.search(r" neighbor [^\s]+", line).group()
                    bgp_group = bgp_group.split()[1]
github napalm-automation / napalm / napalm / junos / junos.py View on Github external
interfaces = dict(interfaces)
            for iface, iface_data in interfaces.items():
                result[iface] = {
                    "is_up": iface_data["is_up"],
                    # For physical interfaces  will always be there, so just
                    # return the value interfaces[iface]['is_enabled']
                    # For logical interfaces if  is present interface is disabled,
                    # otherwise interface is enabled
                    "is_enabled": (
                        True
                        if iface_data["is_enabled"] is None
                        else iface_data["is_enabled"]
                    ),
                    "description": (iface_data["description"] or ""),
                    "last_flapped": float((iface_data["last_flapped"] or -1)),
                    "mac_address": napalm.base.helpers.convert(
                        napalm.base.helpers.mac,
                        iface_data["mac_address"],
                        str(iface_data["mac_address"]),
                    ),
                    "speed": -1,
                    "mtu": 0,
                }
                # result[iface]['last_flapped'] = float(result[iface]['last_flapped'])

                match_mtu = re.search(r"(\w+)", str(iface_data["mtu"]) or "")
                mtu = napalm.base.helpers.convert(int, match_mtu.group(0), 0)
                result[iface]["mtu"] = mtu
                match = re.search(r"(\d+|[Aa]uto)(\w*)", iface_data["speed"] or "")
                if match and match.group(1).lower() == "auto":
                    match = re.search(
                        r"(\d+)(\w*)", iface_data["negotiated_speed"] or ""
github napalm-automation / napalm / napalm / eos / eos.py View on Github external
interfaces[interface]["is_up"] = False
                if values["interfaceStatus"] == "disabled":
                    interfaces[interface]["is_enabled"] = False
                else:
                    interfaces[interface]["is_enabled"] = True

            interfaces[interface]["description"] = values["description"]

            interfaces[interface]["last_flapped"] = values.pop(
                "lastStatusChangeTimestamp", -1.0
            )

            interfaces[interface]["mtu"] = int(values["mtu"])
            interfaces[interface]["speed"] = int(values["bandwidth"] * 1e-6)
            interfaces[interface]["mac_address"] = napalm.base.helpers.convert(
                napalm.base.helpers.mac, values.pop("physicalAddress", "")
            )

        return interfaces
github napalm-automation / napalm / napalm / nxos / nxos.py View on Github external
hop_regex = "".join(_HOP_ENTRY + _HOP_ENTRY_PROBE * probes)
        traceroute_result["success"] = {}
        if traceroute_raw_output:
            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]
                    ip_address_raw = hop_details[4 + probe_index * 5]
                    ip_address = napalm.base.helpers.convert(
                        napalm.base.helpers.ip, ip_address_raw, ip_address_raw
                    )
                    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
github napalm-automation / napalm / napalm / iosxr / iosxr.py View on Github external
"interface_list": [],
        }

        facts_rpc_request = "\
        "

        facts_rpc_reply = ETREE.fromstring(self.device.make_rpc_call(facts_rpc_request))
        system_time_xpath = ".//SystemTime/Uptime"
        platform_attr_xpath = ".//RackTable/Rack/Attributes/BasicInfo"
        system_time_tree = facts_rpc_reply.xpath(system_time_xpath)[0]
        try:
            platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)[0]
        except IndexError:
            platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)

        hostname = napalm.base.helpers.convert(
            str, napalm.base.helpers.find_txt(system_time_tree, "Hostname")
        )
        uptime = napalm.base.helpers.convert(
            int, napalm.base.helpers.find_txt(system_time_tree, "Uptime"), -1
        )
        serial = napalm.base.helpers.convert(
            str, napalm.base.helpers.find_txt(platform_attr_tree, "SerialNumber")
        )
        os_version = napalm.base.helpers.convert(
            str, napalm.base.helpers.find_txt(platform_attr_tree, "SoftwareRevision")
        )
        model = napalm.base.helpers.convert(
            str, napalm.base.helpers.find_txt(platform_attr_tree, "ModelName")
        )
        interface_list = sorted(list(self.get_interfaces().keys()))