Skip to content

Commit

Permalink
Merge pull request #1767 from napalm-automation/netaddr_ipaddr
Browse files Browse the repository at this point in the history
refactor: replace netaddr with ipaddress
Resolves #1759
  • Loading branch information
bewing committed Oct 14, 2022
2 parents d978c3d + 4869ca5 commit 0608244
Show file tree
Hide file tree
Showing 13 changed files with 338 additions and 48 deletions.
15 changes: 12 additions & 3 deletions napalm/base/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Helper functions for the NAPALM base."""
import ipaddress
import itertools
import logging

Expand All @@ -14,7 +15,6 @@
import textfsm
from lxml import etree
from netaddr import EUI
from netaddr import IPAddress
from netaddr import mac_unix
from netutils.config.parser import IOSConfigParser

Expand Down Expand Up @@ -537,10 +537,19 @@ def ip(addr: str, version: Optional[int] = None) -> str:
>>> ip('2001:0dB8:85a3:0000:0000:8A2e:0370:7334')
u'2001:db8:85a3::8a2e:370:7334'
"""
addr_obj = IPAddress(addr)
scope = ""
if "%" in addr:
addr, scope = addr.split("%", 1)
addr_obj = ipaddress.ip_address(addr)
if version and addr_obj.version != version:
raise ValueError("{} is not an ipv{} address".format(addr, version))
return str(addr_obj)
if addr_obj.version == 6 and addr_obj.ipv4_mapped is not None:
return_addr = "%s:%s" % ("::ffff", addr_obj.ipv4_mapped)
else:
return_addr = str(addr_obj)
if scope:
return_addr = "%s%%%s" % (return_addr, scope)
return return_addr


def as_number(as_number_val: str) -> int:
Expand Down
15 changes: 6 additions & 9 deletions napalm/eos/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,12 @@
import time
import importlib
import inspect
import ipaddress
import json
import socket

from datetime import datetime
from collections import defaultdict
from netaddr import IPAddress
from netaddr import IPNetwork

from netaddr.core import AddrFormatError

# third party libs
import pyeapi
Expand Down Expand Up @@ -1134,7 +1131,7 @@ def parse_options(options, default_value=False):
# will try to parse the neighbor name
# which sometimes is the IP Address of the neigbor
# or the name of the BGP group
IPAddress(group_or_neighbor)
ipaddress.ip_address(group_or_neighbor)
# if passes the test => it is an IP Address, thus a Neighbor!
peer_address = group_or_neighbor
if peer_address not in bgp_neighbors:
Expand Down Expand Up @@ -1162,7 +1159,7 @@ def parse_options(options, default_value=False):
bgp_neighbors[peer_address].update(
parse_options(options, default_value)
)
except AddrFormatError:
except ValueError:
# exception trying to parse group name
# group_or_neighbor represents the name of the group
group_name = group_or_neighbor
Expand Down Expand Up @@ -1425,7 +1422,7 @@ def get_route_to(self, destination="", protocol="", longer=False):
protocol = "connected"

ipv = ""
if IPNetwork(destination).version == 6:
if ipaddress.ip_network(destination).version == 6:
ipv = "v6"

commands = []
Expand Down Expand Up @@ -1532,7 +1529,7 @@ def get_route_to(self, destination="", protocol="", longer=False):
.get("peerEntry", {})
.get("peerAddr", "")
)
except AddrFormatError:
except ValueError:
remote_address = napalm.base.helpers.ip(
bgp_route_details.get("peerEntry", {}).get(
"peerAddr", ""
Expand Down Expand Up @@ -1911,7 +1908,7 @@ def _append(bgp_dict, peer_info):
summary_commands.append("show ipv6 bgp summary vrf all")
else:
try:
peer_ver = IPAddress(neighbor_address).version
peer_ver = ipaddress.ip_address(neighbor_address).version
except Exception as e:
raise e

Expand Down
11 changes: 5 additions & 6 deletions napalm/ios/ios.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
# the License.
import copy
import functools
import ipaddress
import os
import re
import socket
Expand All @@ -22,8 +23,6 @@
import uuid
from collections import defaultdict

from netaddr import IPNetwork
from netaddr.core import AddrFormatError
from netmiko import FileTransfer, InLineTransfer

import napalm.base.constants as C
Expand Down Expand Up @@ -3074,17 +3073,17 @@ def get_route_to(self, destination="", protocol="", longer=False):
vrf = ""
ip_version = None
try:
ip_version = IPNetwork(destination).version
except AddrFormatError:
ip_version = ipaddress.ip_network(destination).version
except ValueError:
return "Please specify a valid destination!"
if ip_version == 4: # process IPv4 routing table
if vrf == "":
vrfs = sorted(self._get_vrfs(ip_version))
else:
vrfs = [vrf] # VRFs where IPv4 is enabled
vrfs.append("default") # global VRF
ipnet_dest = IPNetwork(destination)
prefix = str(ipnet_dest.network)
ipnet_dest = ipaddress.ip_network(destination)
prefix = str(ipnet_dest.network_address)
netmask = ""
routes = {}
if "/" in destination:
Expand Down
12 changes: 5 additions & 7 deletions napalm/iosxr/iosxr.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@
# import stdlib
import re
import copy
import ipaddress
from collections import defaultdict
import logging

# import third party lib
from lxml import etree as ETREE

from netaddr import IPAddress # needed for traceroute, to check IP version
from netaddr.core import AddrFormatError

from napalm.pyIOSXR import IOSXR
from napalm.pyIOSXR.exceptions import ConnectError
from napalm.pyIOSXR.exceptions import TimeoutError
Expand Down Expand Up @@ -1733,8 +1731,8 @@ def get_route_to(self, destination="", protocol="", longer=False):

ipv = 4
try:
ipv = IPAddress(network).version
except AddrFormatError:
ipv = ipaddress.ip_address(network).version
except ValueError:
logger.error("Wrong destination IP Address format supplied to get_route_to")
raise TypeError("Wrong destination IP Address!")

Expand Down Expand Up @@ -2187,8 +2185,8 @@ def traceroute(

ipv = 4
try:
ipv = IPAddress(destination).version
except AddrFormatError:
ipv = ipaddress.ip_address(destination).version
except ValueError:
logger.error(
"Incorrect format of IP Address in traceroute \
with value provided:%s"
Expand Down
11 changes: 5 additions & 6 deletions napalm/iosxr_netconf/iosxr_netconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import re
import copy
import difflib
import ipaddress
import logging

# import third party lib
Expand All @@ -31,8 +32,6 @@
from ncclient.operations.errors import TimeoutExpiredError
from lxml import etree as ETREE
from lxml.etree import XMLSyntaxError
from netaddr import IPAddress # needed for traceroute, to check IP version
from netaddr.core import AddrFormatError

# import NAPALM base
from napalm.iosxr_netconf import constants as C
Expand Down Expand Up @@ -2481,8 +2480,8 @@ def get_route_to(self, destination="", protocol="", longer=False):

ipv = 4
try:
ipv = IPAddress(network).version
except AddrFormatError:
ipv = ipaddress.ip_address(network).version
except ValueError:
logger.error("Wrong destination IP Address format supplied to get_route_to")
raise TypeError("Wrong destination IP Address!")

Expand Down Expand Up @@ -2952,8 +2951,8 @@ def traceroute(

ipv = 4
try:
ipv = IPAddress(destination).version
except AddrFormatError:
ipv = ipaddress.ip_address(destination).version
except ValueError:
logger.error(
"Incorrect format of IP Address in traceroute \
with value provided:%s"
Expand Down
11 changes: 5 additions & 6 deletions napalm/nxos/nxos.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations under
# the License.

import ipaddress
import json
import os
import re
Expand Down Expand Up @@ -42,8 +43,6 @@
DefaultDict,
)

from netaddr import IPAddress
from netaddr.core import AddrFormatError
from netmiko import file_transfer
from requests.exceptions import ConnectionError
from netutils.config.compliance import diff_network_config
Expand Down Expand Up @@ -356,8 +355,8 @@ def ping(

version = ""
try:
version = "6" if IPAddress(destination).version == 6 else ""
except AddrFormatError:
version = "6" if ipaddress.ip_address(destination).version == 6 else ""
except ValueError:
# Allow use of DNS names
pass

Expand Down Expand Up @@ -470,8 +469,8 @@ def traceroute(

version = ""
try:
version = "6" if IPAddress(destination).version == 6 else ""
except AddrFormatError:
version = "6" if ipaddress.ip_address(destination).version == 6 else ""
except ValueError:
# Allow use of DNS names
pass

Expand Down
11 changes: 4 additions & 7 deletions napalm/nxos_ssh/nxos_ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@

# import stdlib
from builtins import super
import ipaddress
import re
import socket

# import third party lib
from netaddr import IPAddress, IPNetwork
from netaddr.core import AddrFormatError

# import NAPALM Base
from napalm.base import helpers
from napalm.base.exceptions import CommandErrorException, ReplaceConfigException
Expand Down Expand Up @@ -953,7 +950,7 @@ def _get_ntp_entity(self, peer_type):
# Skip first two lines and last line of command output
if line == "" or "-----" in line or "Peer IP Address" in line:
continue
elif IPAddress(len(line.split()[0])).is_unicast:
elif not ipaddress.ip_address(len(line.split()[0])).is_multicast:
peer_addr = line.split()[0]
ntp_entities[peer_addr] = {}
else:
Expand Down Expand Up @@ -1340,8 +1337,8 @@ def get_route_to(self, destination="", protocol="", longer=False):

ip_version = None
try:
ip_version = IPNetwork(destination).version
except AddrFormatError:
ip_version = ipaddress.ip_network(destination).version
except ValueError:
return "Please specify a valid destination!"
if ip_version == 4: # process IPv4 routing table
routes = {}
Expand Down
6 changes: 2 additions & 4 deletions test/base/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,8 @@ def test_ip(self):
* check if IPv6 address returned as expected
"""

self.assertTrue(HAS_NETADDR)

# test that raises AddrFormatError when wrong format
self.assertRaises(AddrFormatError, napalm.base.helpers.ip, "fake")
# test that raises ValueError when wrong format
self.assertRaises(ValueError, napalm.base.helpers.ip, "fake")
self.assertRaises(
ValueError,
napalm.base.helpers.ip,
Expand Down

0 comments on commit 0608244

Please sign in to comment.