Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# test that raises AddrFormatError when wrong format
self.assertRaises(AddrFormatError, napalm.base.helpers.ip, "fake")
self.assertRaises(
ValueError,
napalm.base.helpers.ip,
"2001:db8:85a3::8a2e:370:7334",
version=4,
)
self.assertRaises(ValueError, napalm.base.helpers.ip, "192.168.17.1", version=6)
self.assertEqual(
napalm.base.helpers.ip("2001:0dB8:85a3:0000:0000:8A2e:0370:7334"),
"2001:db8:85a3::8a2e:370:7334",
)
self.assertEqual(
napalm.base.helpers.ip("2001:0DB8::0003", version=6), "2001:db8::3"
)
def _get_bgp_neighbors_core(
neighbor_data, instance=None, uptime_table_items=None
):
"""
Make sure to execute a simple request whenever using
junos > 13. This is a helper used to avoid code redundancy
and reuse the function also when iterating through the list
BGP neighbors under a specific routing instance,
also when the device is capable to return the routing
instance name at the BGP neighbor level.
"""
for bgp_neighbor in neighbor_data:
peer_ip = napalm.base.helpers.ip(bgp_neighbor[0].split("+")[0])
neighbor_details = deepcopy(default_neighbor_details)
neighbor_details.update(
{
elem[0]: elem[1]
for elem in bgp_neighbor[1]
if elem[1] is not None
}
)
if not instance:
# not instance, means newer Junos version,
# as we request everything in a single request
peer_fwd_rti = neighbor_details.pop("peer_fwd_rti")
instance = peer_fwd_rti
else:
# instance is explicitly requests,
# thus it's an old Junos, so we retrieve the BGP neighbors
# this line can be either description or rid info
next_line = lines.pop(0)
desc = re.match(self._RE_BGP_DESC, next_line)
if desc is None:
rid_info = re.match(self._RE_BGP_RID_INFO, next_line)
desc = ""
else:
rid_info = re.match(self._RE_BGP_RID_INFO, lines.pop(0))
desc = desc.group("description")
lines.pop(0)
v4_stats = re.match(self._RE_BGP_PREFIX, lines.pop(0))
v6_stats = re.match(self._RE_BGP_PREFIX, lines.pop(0))
local_as = re.match(self._RE_BGP_LOCAL, lines.pop(0))
data = {
"remote_as": int(neighbor_info.group("as")),
"remote_id": napalm.base.helpers.ip(
get_re_group(rid_info, "rid", "0.0.0.0")
),
"local_as": int(local_as.group("as")),
"description": str(desc),
"address_family": {
"ipv4": {
"sent_prefixes": int(get_re_group(v4_stats, "sent", -1)),
"received_prefixes": int(
get_re_group(v4_stats, "received", -1)
),
"accepted_prefixes": -1,
},
"ipv6": {
"sent_prefixes": int(get_re_group(v6_stats, "sent", -1)),
"received_prefixes": int(
get_re_group(v6_stats, "received", -1)
try:
del neighbor_data_entry[field]
except KeyError:
pass
break
router_id = None
for entry in summary_data:
if not router_id:
router_id = entry["router_id"]
elif entry["router_id"] != router_id:
raise ValueError
# check the router_id looks like an ipv4 address
router_id = napalm.base.helpers.ip(router_id, version=4)
# add parsed data to output dict
bgp_neighbor_data["global"]["router_id"] = router_id
bgp_neighbor_data["global"]["peers"] = {}
for entry in summary_data:
remote_addr = napalm.base.helpers.ip(entry["remote_addr"])
afi = entry["afi"].lower()
# check that we're looking at a supported afi
if afi not in supported_afi:
continue
# get neighbor_entry out of neighbor data
neighbor_entry = None
for neighbor in neighbor_data:
if (
neighbor["afi"].lower() == afi
and napalm.base.helpers.ip(neighbor["remote_addr"]) == remote_addr
"sent_prefixes": int(get_re_group(v4_stats, "sent", -1)),
"received_prefixes": int(
get_re_group(v4_stats, "received", -1)
),
"accepted_prefixes": -1,
},
"ipv6": {
"sent_prefixes": int(get_re_group(v6_stats, "sent", -1)),
"received_prefixes": int(
get_re_group(v6_stats, "received", -1)
),
"accepted_prefixes": -1,
},
},
}
peer_addr = napalm.base.helpers.ip(neighbor_info.group("neighbor"))
vrf = rid_info.group("vrf")
if peer_addr not in bgp_counters[vrf]["peers"]:
bgp_counters[vrf]["peers"][peer_addr] = {
"is_up": False, # if not found, means it was not found in the oper stats
# i.e. neighbor down,
"uptime": 0,
"is_enabled": True,
}
bgp_counters[vrf]["peers"][peer_addr].update(data)
if "default" in bgp_counters:
bgp_counters["global"] = bgp_counters.pop("default")
return dict(bgp_counters)
_DATATYPE_DEFAULT_ = {str: "", int: 0, bool: False, list: []}
bgp_config = {}
if group:
bgp = junos_views.junos_bgp_config_group_table(self.device)
bgp.get(group=group, options={"database": self.junos_config_database})
else:
bgp = junos_views.junos_bgp_config_table(self.device)
bgp.get(options={"database": self.junos_config_database})
neighbor = "" # if no group is set, no neighbor should be set either
bgp_items = bgp.items()
if neighbor:
neighbor_ip = napalm.base.helpers.ip(neighbor)
# Get all policies configured in one go and check if "next-hop self" is found in each policy
# Save the result in a dict indexed by policy name (junos policy-statement)
# The value is a boolean. True if "next-hop self" was found
# The resulting dict (nhs_policies) will be used by _check_nhs to determine if "nhs"
# is configured or not in the policies applied to a BGP neighbor
policy = junos_views.junos_policy_nhs_config_table(self.device)
policy.get(options={"database": self.junos_config_database})
nhs_policies = dict()
for policy_name, is_nhs_list in policy.items():
# is_nhs_list is a list with one element. Ex: [('is_nhs', True)]
is_nhs, boolean = is_nhs_list[0]
nhs_policies[policy_name] = boolean if boolean is not None else False
for bgp_group in bgp_items:
bgp_group_name = bgp_group[0]
int,
napalm.base.helpers.find_txt(
bgp_path,
"AttributesAfterPolicyIn/CommonAttributes/LocalPreference",
),
0,
)
remote_as = napalm.base.helpers.convert(
int,
napalm.base.helpers.find_txt(
bgp_path,
"AttributesAfterPolicyIn/CommonAttributes/NeighborAS",
),
0,
)
remote_address = napalm.base.helpers.ip(
napalm.base.helpers.find_txt(
bgp_path, "PathInformation/NeighborAddress/IPV4Address"
)
or napalm.base.helpers.find_txt(
bgp_path, "PathInformation/NeighborAddress/IPV6Address"
)
)
as_path = " ".join(
[
bgp_as.text
for bgp_as in bgp_path.xpath(
"AttributesAfterPolicyIn/CommonAttributes/NeighborAS/Entry"
)
]
)
next_hop = napalm.base.helpers.find_txt(
def get_ntp_peers(self):
"""Return the NTP peers configured on the device."""
ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
ntp_table.get(options={"database": self.junos_config_database})
ntp_peers = ntp_table.items()
if not ntp_peers:
return {}
return {napalm.base.helpers.ip(peer[0]): {} for peer in ntp_peers}
bgp_neighbor_data[vrf] = {}
bgp_neighbor_data[vrf]["router_id"] = router_id
bgp_neighbor_data[vrf]["peers"] = {}
# add parsed data to output dict
for entry in summary_data:
remote_addr = napalm.base.helpers.ip(entry["remote_addr"])
afi = entry["afi"].lower()
# check that we're looking at a supported afi
if afi not in supported_afi:
continue
# get neighbor_entry out of neighbor data
neighbor_entry = None
for neighbor in neighbor_data:
if (
neighbor["afi"].lower() == afi
and napalm.base.helpers.ip(neighbor["remote_addr"]) == remote_addr
):
neighbor_entry = neighbor
break
# check for proper session data for the afi
if neighbor_entry is None:
continue
elif not isinstance(neighbor_entry, dict):
raise ValueError(
msg="Couldn't find neighbor data for %s in afi %s"
% (remote_addr, afi)
)
# check for admin down state
try:
if "(Admin)" in entry["state"]:
is_enabled = False
# try to get sent prefix count and convert to int, otherwise set to -1
sent_prefixes = int(neighbor_entry.get("sent_prefixes", -1))
else:
received_prefixes = -1
sent_prefixes = -1
uptime = -1
# get description
try:
description = py23_compat.text_type(neighbor_entry["description"])
except KeyError:
description = ""
# check the remote router_id looks like an ipv4 address
remote_id = napalm.base.helpers.ip(neighbor_entry["remote_id"], version=4)
if remote_addr not in bgp_neighbor_data["global"]["peers"]:
bgp_neighbor_data["global"]["peers"][remote_addr] = {
"local_as": napalm.base.helpers.as_number(entry["local_as"]),
"remote_as": napalm.base.helpers.as_number(entry["remote_as"]),
"remote_id": remote_id,
"is_up": is_up,
"is_enabled": is_enabled,
"description": description,
"uptime": uptime,
"address_family": {
afi: {
"received_prefixes": received_prefixes,
"accepted_prefixes": accepted_prefixes,
"sent_prefixes": sent_prefixes,
}