avocado.utils.network package
Submodules
avocado.utils.network.common module
Utility helpers for executing shell commands on local or remote hosts.
This module centralizes the logic used by network utilities to run commands either on the local machine or through a remote session, with optional privilege escalation via ‘sudo’.
- avocado.utils.network.common.run_command(command, host, sudo=False)
Executes a given command on a specified host, either locally or remotely.
This function determines if the command should be run on the local machine or a remote host based on the type of the ‘host’ object. It can also execute commands with superuser privileges if specified.
- Parameters:
command (str) – The command string to be executed.
host (object) – The host object where the command will be run. If host.__class__.__name__ is “LocalHost”, the command is run locally. Otherwise, it’s treated as a remote host with a ‘remote_session’ attribute supporting a ‘cmd’ method.
sudo (bool) – If True, the command will be executed with ‘sudo’. Defaults to False.
- Returns:
The standard output of the executed command, decoded as UTF-8.
- Return type:
- Raises:
AttributeError – If ‘host’ is not “LocalHost” and does not have a ‘remote_session.cmd’ method.
avocado.utils.network.exceptions module
Exception hierarchy for network utilities.
This module defines custom exception classes used throughout network utilities.
All specific network errors should inherit from NWException so they can
be handled collectively when required.
avocado.utils.network.hosts module
Provides a high-level API for interacting with network hosts.
This module offers classes to represent and manage local and remote hosts, allowing users to query network interface information, validate MAC addresses, and retrieve routing details. It abstracts the underlying command execution for common network-related tasks.
- class avocado.utils.network.hosts.Host(host)
Bases:
objectThis class represents a base Host and shouldn’t be instantiated directly.
Use one of the child classes (LocalHost or RemoteHost).
During the initialization of a child, network interfaces can be detected and made available via the interfaces attribute. This attribute can be accessed on both LocalHost and RemoteHost instances.
So, for instance, you could have a local and a remote host:
remote = RemoteHost(host='foo', port=22, username='foo', password='bar') local = LocalHost()
You can iterate over the network interfaces of any host:
for i in remote.interfaces: print(f"Interface: {i.name}, Link Up: {i.is_link_up()}")
Initializes the base Host class.
This constructor is intended to be called by sub-classes. Direct initialization of Host will raise a TypeError.
- Parameters:
host (str) – The hostname or IP address of the host. For LocalHost, this typically defaults to ‘localhost’.
- Raises:
TypeError – If the Host class is instantiated directly.
- get_all_hwaddr()
Gets a list of all MAC addresses on the host.
Executes ‘ip -j address’ and parses the JSON output to extract MAC addresses.
- Returns:
A list of strings, where each string is a MAC address found on the host.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the command execution fails or the JSON output cannot be parsed.
- get_default_route_interface()
Gets the name(s) of the interface(s) used for the default route.
Executes ‘ip -j route list default’ and parses the JSON output to extract the device name(s) associated with the default route(s).
- Returns:
A list of strings, where each string is the name of an interface used for a default route. Can be empty if no default route is found or if the ‘dev’ field is missing.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the command execution fails or the JSON output cannot be parsed.
- get_interface_by_hwaddr(mac)
Retrieves a network interface that has a specific MAC address.
- Parameters:
mac (str) – The MAC address to search for. The MAC address format should be consistent with the output of interface.get_hwaddr().
- Returns:
The NetworkInterface object matching the given MAC address, or None if no interface is found with that MAC address.
- Return type:
NetworkInterface or None
- get_interface_by_ipaddr(ipaddr)
Retrieves a network interface that has a specific IP address.
- Parameters:
ipaddr (str) – The IP address to search for among the host’s network interfaces.
- Returns:
The NetworkInterface object matching the given IP address, or None if no interface is found with that IP.
- Return type:
NetworkInterface or None
- property interfaces
Retrieves the network interfaces for the host.
Detects network interface names by listing contents of ‘/sys/class/net’. Excludes ‘bonding_masters’ from the list.
- Returns:
A list of NetworkInterface objects for all network interfaces on the host.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the command to list interfaces fails or the output cannot be processed.
- static validate_mac_addr(mac_id)
Checks if a given MAC address string is in a valid format.
A valid MAC address is defined as a 12-digit hexadecimal number, with pairs of digits separated by colons (e.g., ‘36:84:37:5a:ea:02’).
- class avocado.utils.network.hosts.LocalHost(host='localhost')
Bases:
HostRepresents the local machine, inheriting from Host.
Use this class to get information about the network configuration of the machine where the script is running.
Example:
local = LocalHost() print(f"Local hostname: {local.host}") for iface in local.interfaces: print(f"Interface: {iface.name}")
Initializes a LocalHost instance.
- Parameters:
host (str) – The name to assign to the local host. Defaults to “localhost”.
- class avocado.utils.network.hosts.RemoteHost(host, username, port=22, key=None, password=None)
Bases:
HostRepresents a remote machine, inheriting from Host.
This class manages an SSH connection to a remote host to execute commands and retrieve network information. It requires credentials (username and either password or SSH key) to establish the connection.
The class can be used as a context manager to ensure the SSH session is properly closed.
Example with password:
remote_details = { 'host': '192.168.0.1', 'port': 22, 'username': 'user', 'password': 'secure-password' } with RemoteHost(**remote_details) as remote: print(f"Remote interfaces on {remote.host}:") for iface in remote.interfaces: print(f"- {iface.name}")
Example with SSH key:
remote_key_details = { 'host': 'server.example.com', 'username': 'admin', 'key': '/path/to/private/key' } with RemoteHost(**remote_key_details) as remote_server: # ... interact with remote_server ... pass # Session closes automatically on exit
Initializes a RemoteHost instance and establishes an SSH connection.
- Parameters:
host (str) – The hostname or IP address of the remote host.
username (str) – The username for SSH authentication.
port (int) – The SSH port on the remote host. Defaults to 22.
key (str) – The file path to the private SSH key for key-based authentication. Defaults to None.
password (str) – The password for password-based authentication. Defaults to None.
- Raises:
avocado.utils.network.exceptions.NWException – If the SSH connection to the remote host fails.
avocado.utils.network.interfaces module
Network interface management utilities.
This module defines the NetworkInterface class, which provides a high-level, distribution-aware wrapper for performing common network configuration tasks on both local and remote hosts. Functionality includes, but is not limited to:
Querying and manipulating interface attributes (MAC, MTU, IP addresses, VLANs, bonding information).
Persisting interface settings to the appropriate configuration files for RHEL/Fedora and SuSE families, with support for NetworkManager connection profiles on modern releases (RHEL ≥ 9, SuSE ≥ 16).
Executing connectivity checks such as ICMP ping and detecting packet loss or interface link status.
Gracefully handling errors through custom exceptions defined in avocado.utils.network.exceptions.
All shell commands are executed via avocado.utils.network.common.run_command, allowing seamless operation on either a local LocalHost instance or a remote RemoteHost session.
- class avocado.utils.network.interfaces.NetworkInterface(if_name, host, if_type='Ethernet')
Bases:
objectRepresents a network card interface (NIC).
An “NetworkInterface” is attached to some host. This could be an instance of LocalHost or RemoteHost. If a RemoteHost then all commands will be executed on a remote_session (host.remote_session). Otherwise will be executed locally.
Here you will find a few methods to perform basic operations on a NIC.
Initializes a NetworkInterface object.
- Parameters:
- add_ipaddr(ipaddr, netmask)
Add an IP Address (with netmask) to the interface.
This method will try to add a new ipaddr/netmask this interface, if fails it will raise a NWException.
You must have sudo permissions to run this method on a host.
- Parameters:
- Raises:
avocado.utils.network.exceptions.NWException – If adding the IP address fails.
- add_vlan_tag(vlan_num, vlan_name=None)
Configure 802.1Q VLAN tagging to the interface.
This method will attempt to add a VLAN tag to this interface. If it fails, the method will raise a NWException.
- Parameters:
- Raises:
avocado.utils.network.exceptions.NWException – If adding the VLAN tag fails.
- are_packets_lost(peer_ip, options=None, sudo=False)
Check packet loss that occurs during ping.
Function returns False for 0% packet loss and True if packet loss occurs.
- Parameters:
- Returns:
False for 0% packet loss, True otherwise.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the ping command fails.
- bring_down()
Shutdown the interface.
This will shutdown the interface link. Be careful, you might lost connection to the host.
You must have sudo permissions to run this method on a host.
- Raises:
avocado.utils.network.exceptions.NWException – If the command to bring down the interface fails.
- bring_up()
Wake-up the interface.
This will wake-up the interface link.
You must have sudo permissions to run this method on a host.
- Raises:
avocado.utils.network.exceptions.NWException – If the command to bring up the interface fails.
- property config_file_path
Gets the directory path for network interface configuration files.
The path is determined based on the detected Linux distribution. Supports RHEL/Fedora and SuSE distributions.
- Returns:
The absolute path to the configuration directory, or None if the distribution is not supported.
- Return type:
str or None
- property config_filename
Gets the full path to the network interface configuration file.
The path is determined based on the detected Linux distribution. Supports RHEL/Fedora and SuSE distributions, with different paths for newer versions (RHEL 9+, SuSE 16+).
- Returns:
The absolute path to the configuration file.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the distribution is not supported.
- flush_ipaddr()
Flush all the IP address for this interface.
This method will try to flush the ip address from this interface and if fails it will raise a NWException. Be careful, you can lost connection.
You must have sudo permissions to run this method on a host.
- Raises:
avocado.utils.network.exceptions.NWException – If flushing the IP addresses fails.
- get_device_IPI_name()
Convert IO device name to device_ipi names according to “/proc/interrupts” context. Ex: vnic@30000009 to vnic-30000009
- Returns:
A converted Network device according to device_ipi name.
- Return type:
str or None
- get_hwaddr()
Get the Hardware Address (MAC) of this interface.
This method will try to get the address and if fails it will raise a NWException.
- Returns:
The hardware address (MAC address).
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If fetching the hardware address fails.
- get_ipaddrs(version=4)
Get the IP addresses from a network interface.
Interfaces can hold multiple IP addresses. This method will return a list with all addresses on this interface.
- Parameters:
version (int) – Address Family Version (4 or 6). This must be a integer and default is 4.
- Returns:
IP address as string.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If an unsupported IP version is provided.
- get_mtu()
Return the current MTU value of this interface.
This method will try to get the current MTU value, if fails will raise a NWException.
- Returns:
The MTU value of the interface.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the MTU value cannot be retrieved.
- is_admin_link_up()
Check the admin link state is up or not.
- Returns:
True or False, True if network interface state is ‘UP’ otherwise will return False.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the link state cannot be retrieved.
- is_available()
Check if interface is available.
This method checks if the interface is available.
- Returns:
True if the interface exists, False otherwise.
- Return type:
- is_bond()
Check if interface is a bonding device.
This method checks if the interface is a bonding device or not.
- Returns:
True if the interface is a bonding device, False otherwise.
- Return type:
- is_link_up()
Check if the interface is up or not.
- Returns:
True or False. True if admin link state and operational link state is up otherwise will return False.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the link state cannot be retrieved.
- is_operational_link_up()
Check Operational link state is up or not.
- Returns:
True or False. True if operational link state is LOWER_UP, otherwise will return False.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the link state cannot be retrieved.
- is_sriov()
Check if interface is a SRIOV virtual interface.
This method checks if the interface is SRIOV logical interface or not.
- Returns:
True if the interface is an SRIOV VF, False otherwise.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the sysfs file for the device does not exist.
- is_veth()
Check if interface is a Virtual Ethernet.
This method checks if the interface is a Virtual Ethernet or not.
- Returns:
True if the interface is a veth device, False otherwise.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the sysfs file for the device does not exist.
- is_vnic()
Check if interface is a virtual network.
This method checks if the interface is a virtual NIC or not.
- Returns:
True if the interface is a virtual NIC, False otherwise.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If the sysfs file for the device does not exist.
- static netmask_to_cidr(netmask)
Function is used to check the netmask value and convert
it into short form (mask) of netmask values Example : 255.255.255.0 = 24 255.255.252.0 = 22
- nm_flush_ipaddr()
Remove all the IPv4 address for this interface by using IP tool.
This method will explicitly identifies all available IP addresses with netmask of interfaces and deletes them.
You must have sudo permissions to run this method on a host.
- Raises:
avocado.utils.network.exceptions.NWException – If flushing the IP addresses fails.
- ping_check(peer_ip, count=2, options=None)
This method will try to ping a peer address (IPv4 or IPv6).
You should provide a IPv4 or IPV6 that would like to ping. This method will try to ping the peer and if fails it will raise a NWException.
- Parameters:
- Raises:
avocado.utils.network.exceptions.NWException – If the ping command fails.
- static ping_flood(int_name, peer_ip, ping_count)
Start ping to remote machine with “-f” [ flood ] option, on given interface.
Also this function enables to track the live data to determine the ping flood failure, in case of failure the program will exit.
- remove_all_vlans()
Remove all VLANs of this interface.
This method will remove all the VLAN interfaces associated by the interface.
- Raises:
avocado.utils.network.exceptions.NWException – If removing the VLAN interfaces fails.
- remove_cfg_file()
Remove any config files that is created as a part of the test.
- remove_ipaddr(ipaddr, netmask)
Removes an IP address from this interface.
This method will try to remove the address from this interface and if fails it will raise a NWException. Be careful, you can lost connection.
You must have sudo permissions to run this method on a host.
- Parameters:
- Raises:
avocado.utils.network.exceptions.NWException – If removing the IP address fails.
- remove_link()
Deletes virtual interface link.
This method will try to delete the virtual device link and the interface will no more be listed with ‘ip a’ and if fails it will raise a NWException. Be careful, you can lost connection.
You must have sudo permissions to run this method on a host.
- Raises:
avocado.utils.network.exceptions.NWException – If deleting the link fails.
- remove_vlan_by_tag(vlan_num)
Remove the VLAN of the interface by tag number.
This method will try to remove the VLAN tag of this interface. If it fails, the method will raise a NWException.
- Parameters:
vlan_num (int) – VLAN ID
- Returns:
True or False, True if it found the VLAN interface and removed it successfully, otherwise it will return False.
- Return type:
- Raises:
avocado.utils.network.exceptions.NWException – If removing the VLAN tag fails.
- restore_from_backup()
Revert interface file from backup.
This method checks if a backup version is available for given interface then it copies backup file to interface file in /sysfs path.
- Raises:
avocado.utils.network.exceptions.NWException – If the backup file is not available.
- restore_slave_cfg_file()
Restore or delete slave config files.
- Raises:
avocado.utils.network.exceptions.NWException – If the config file cannot be restored.
- save(ipaddr, netmask)
Save current interface IP Address to the system configuration file.
If the ipaddr is valid (currently being used by the interface) this will try to save the current settings into /etc/. This check is necessary to avoid inconsistency. Before save, you should add_ipaddr, first.
Currently, only RHEL, Fedora and SuSE are supported. And this will create a backup file of your current configuration if found.
:param ipaddr : IP Address which need to configure for interface :type ipaddr: str :param netmask: Network mask which is associated to the provided IP :type netmask: str :raises avocado.utils.network.exceptions.NWException: If ipaddr is not configured on the interface or the distribution is not supported.
- set_hwaddr(hwaddr)
Sets a Hardware Address (MAC Address) to the interface.
This method will try to set a new hwaddr to this interface, if fails it will raise a NWException.
You must have sudo permissions to run this method on a host.
- Parameters:
hwaddr (str) – Hardware Address (Mac Address).
- Raises:
avocado.utils.network.exceptions.NWException – If the command to set the MAC address fails.
- set_mtu(mtu, timeout=30)
Sets a new MTU value to this interface.
This method will try to set a new MTU value to this interface, if fails it will raise a NWException. Also it will wait until the Interface is up before returning or until timeout be reached.
You must have sudo permissions to run this method on a host.
- Parameters:
- Raises:
avocado.utils.network.exceptions.NWException – If setting the MTU fails.
- property slave_config_filename
Gets the configuration filenames for all slave interfaces of a bond.
This is only applicable for ‘Bond’ type interfaces.
- static validate_ipv4_format(ip)
Validates IPv4 address with following format set.
A string in decimal-dot notation, consisting of four decimal integers in the inclusive range 0-255,separated by dots (e.g- 192.168.0.1).Each integer represents an octet in the address.
An integer that fits into 32 bits.
An integer packed into a bytes object of length 4.
And for IP address which are not met above conditions, raises AddressValueError and returns False.
- static validate_ipv4_netmask_format(netmask)
Validates IPv4 Netmask address with following format set.
A string in decimal-dot notation,consisting of four decimal integers starting from 255 and octets separated by dots (e.g 255.255.255.0)
An integer packed into a bytes object of length 4
And for Netmask which are not met above conditions, [ eg : 255.0.255.0, 255.255.255, 255.255.255.256, 255.255.255.255.0] returns False.
avocado.utils.network.ports module
Module with network related utility functions.
- avocado.utils.network.ports.FAMILIES = (AddressFamily.AF_INET, AddressFamily.AF_INET6)
Families taken into account in this class
- avocado.utils.network.ports.PROTOCOLS = (SocketKind.SOCK_STREAM, SocketKind.SOCK_DGRAM)
Protocols taken into account in this class
- class avocado.utils.network.ports.PortTracker
Bases:
BorgTracks ports used in the host machine.
Initializes the PortTracker instance.
- find_free_port(start_port=None)
Finds and registers a free port.
It starts searching from start_port if provided, otherwise it uses the default self.start_port.
- register_port(port)
Registers a port as being in use.
- Parameters:
port (int) – The port number to register.
- Returns:
The registered port number if successful.
- Return type:
- Raises:
ValueError – If the port is already in use or cannot be registered.
- avocado.utils.network.ports.find_free_port(start_port=1024, end_port=65535, address='localhost', sequent=False, family=AddressFamily.AF_INET, protocol=SocketKind.SOCK_STREAM)
Return a host free port in the range [start_port, end_port].
- Parameters:
start_port (int) – header of candidate port range, defaults to 1024
end_port (int) – ender of candidate port range, defaults to 65535
address (str) – Socket address to bind or connect
sequent (bool) – Find port sequentially, random order if it’s False
family (socket.AddressFamily.AF_*) – Default is socket.AF_INET. Accepted values are: socket.AF_INET or socket.AF_INET6.
protocol (socket.AddressFamily.SOCK_*) – Protocol type. Default is socket.SOCK_STREAM (TCP). Accepted values are: socket.SOCK_STREAM or socket.SOCK_DGRAM.
- Returns:
A free port number, or None if no free port is found.
- Return type:
int or None if no free port found
- avocado.utils.network.ports.find_free_ports(start_port, end_port, count, address='localhost', sequent=False, family=AddressFamily.AF_INET, protocol=SocketKind.SOCK_STREAM)
Return a number of host free ports in the range [start_port, end_port].
- Parameters:
start_port (int) – header of candidate port range
end_port (int) – ender of candidate port range
count (int) – Initial number of ports known to be free in the range.
address (str) – Socket address to bind or connect
sequent (bool) – Find port sequentially, random order if it’s False
family (socket.AddressFamily.AF_*) – Default is socket.AF_INET. Accepted values are: socket.AF_INET or socket.AF_INET6.
protocol (socket.AddressFamily.SOCK_*) – Protocol type. Default is socket.SOCK_STREAM (TCP). Accepted values are: socket.SOCK_STREAM or socket.SOCK_DGRAM.
- Returns:
A list of free port numbers.
- Return type:
- avocado.utils.network.ports.is_port_available(port, address, family=AddressFamily.AF_INET, protocol=SocketKind.SOCK_STREAM)
Return True if the given port is available for use.
- Parameters:
port (int) – Port value to check.
address (str) – Address to use this port.
family (socket.AddressFamily.AF_*) – Default is socket.AF_INET. Accepted values are: socket.AF_INET or socket.AF_INET6.
protocol (socket.AddressFamily.SOCK_*) – Protocol type. Default is socket.SOCK_STREAM (TCP). Accepted values are: socket.SOCK_STREAM or socket.SOCK_DGRAM.
- Returns:
True if the port is available, False otherwise.
- Return type: