Skip to content

Commit

Permalink
Merge pull request #783 from Bastian-Krause/bst/shelldriver-ips
Browse files Browse the repository at this point in the history
driver: shelldriver: add get_default_interface_device_name()/get_ip_interfaces()
  • Loading branch information
jluebbe authored Jun 11, 2021
2 parents a6b55b9 + c129fce commit 740d3af
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions labgrid/driver/shelldriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import re
import time
import shlex
import ipaddress

import attr
from pexpect import TIMEOUT
import xmodem
Expand Down Expand Up @@ -536,3 +538,58 @@ def run_script_file(self, scriptfile: str, *args, timeout: int = 60):
IOError: if the provided localfile could not be found
"""
return self._run_script_file(scriptfile, *args, timeout=timeout)

@Driver.check_active
def get_default_interface_device_name(self, version=4):
""" Retrieve the default route's interface device name.
Args:
version (int): IP version
Returns:
Name of the device of the default route
Raises:
ExecutionError: if no or multiple routes are set up
"""
assert version in (4, 6)

regex = r"""default\s+via # leading strings
\s+\S+ # IP address
\s+dev\s+(\w+) # interface"""

default_route = self._run_check(f"ip -{version} route list default")
matches = re.findall(regex, "\n".join(default_route), re.X)

if not matches:
raise ExecutionError(f"No IPv{version} default route found")
if len(matches) > 1:
raise ExecutionError(f"Multiple IPv{version} default routes found")

return matches[0]

@Driver.check_active
def get_ip_addresses(self, device=None):
""" Retrieves IP addresses for given interface name.
Note that although the return type is named IPv4Interface/IPv6Interface, it contains an IP
address with the corresponding network prefix.
Args:
device (str): Name of the interface to query, defaults to default route's device name.
Returns:
List of IPv4Interface or IPv6Interface objects
"""
if device is None:
device = self.get_default_interface_device_name()

regex = r"""\d+: # leading number
\s+\w+ # interface name
\s+inet6?\s+(\S+) # IP address, prefix
.*global # global scope, not host scope"""

ip_show = self._run_check(f"ip -o addr show dev {device}")
matches = re.findall(regex, "\n".join(ip_show), re.X)

return list(map(ipaddress.ip_interface, matches))

0 comments on commit 740d3af

Please sign in to comment.