From f0d842b8e3158bb0f51d6e7095bcd8a030bb2c2e Mon Sep 17 00:00:00 2001 From: Sebastian Mitterle Date: Fri, 22 Dec 2023 08:16:28 -0500 Subject: [PATCH] utils_net: get default gateway for specific interface Add optional parameter in order to retrieve the default gateway for a specific interface. On a system with two interfaces, the routes might look like ``` default via 10.172.161.254 dev enc1 proto dhcp src 10.172.160.70 metric 100 default via 192.168.126.1 dev enc2 proto dhcp src 192.168.126.48 metric 102 ``` Filtering only by default will return two ips ``` 10.172.161.254 192.168.126.1 ``` The change allows us to select the interface and thus retrieve only ``` 192.168.126.1 ``` Signed-off-by: Sebastian Mitterle --- virttest/utils_net.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/virttest/utils_net.py b/virttest/utils_net.py index af573004f4..24e596e792 100644 --- a/virttest/utils_net.py +++ b/virttest/utils_net.py @@ -3893,7 +3893,7 @@ def get_host_iface(): def get_default_gateway(iface_name=False, session=None, ip_ver='ipv4', - force_dhcp=False): + force_dhcp=False, target_iface=None): """ Get the Default Gateway or Interface of host or guest. @@ -3901,6 +3901,7 @@ def get_default_gateway(iface_name=False, session=None, ip_ver='ipv4', (False) is returned, defaults to False :param session: shell/console session if any, defaults to None :param ip_ver: ip version, defaults to 'ipv4' + :param target_iface: if given, get default gateway only for this device :return: default gateway of target iface """ if ip_ver == 'ipv4': @@ -3911,10 +3912,14 @@ def get_default_gateway(iface_name=False, session=None, ip_ver='ipv4', raise ValueError(f'Unrecognized IP version {ip_ver}') if force_dhcp: ip_cmd = ip_cmd + '|grep dhcp' + if target_iface: + regex = "default.*%s" % target_iface + else: + regex = "default" if iface_name: - cmd = "%s | awk '/default/ { print $5 }'" % ip_cmd + cmd = "%s | awk '/%s/ { print $5 }'" % (ip_cmd, regex) else: - cmd = "%s | awk '/default/ { print $3 }'" % ip_cmd + cmd = "%s | awk '/%s/ { print $3 }'" % (ip_cmd, regex) try: _, output = utils_misc.cmd_status_output(cmd, shell=True, session=session) if session: