예제 #1
0
 def _get_interface_details(self, version=None):
     cmd = "ip -j link show {}".format(self.name)
     if version:
         cmd = "ip -{} -j address show {}".format(version, self.name)
     output = run_command(cmd, self.host)
     try:
         result = json.loads(output)
         for item in result:
             if item.get('ifname') == self.name:
                 return item
         raise NWException("Interface not found")
     except (NWException, json.JSONDecodeError):
         msg = "Unable to get the details of interface {}".format(self.name)
         LOG.error(msg)
         raise NWException(msg)
예제 #2
0
 def _move_file_to_backup(self, filename, ignore_missing=True):
     destination = "{}.backup".format(filename)
     if os.path.exists(filename):
         shutil.move(filename, destination)
     else:
         if not ignore_missing:
             raise NWException("%s interface not available" % self.name)
예제 #3
0
 def _get_bondinterface_details(self):
     cmd = (f"cat /sys/class/net/{self.name}/bonding/mode "
            f"/sys/class/net/{self.name}/bonding/slaves")
     try:
         mode, slaves = run_command(cmd, self.host).splitlines()
         return {"mode": mode.split(), "slaves": slaves.split()}
     except Exception:
         raise NWException(f"Slave interface not found for "
                           f"the bond {self.name}")
예제 #4
0
 def _get_bondinterface_details(self):
     cmd = "cat /sys/class/net/{}/bonding/mode \
            /sys/class/net/{}/bonding/slaves".format(self.name, self.name)
     try:
         mode, slaves = run_command(cmd, self.host).splitlines()
         return {'mode': mode.split(), 'slaves': slaves.split()}
     except Exception:
         raise NWException(
             "Slave interface not found for the bond {}".format(self.name))
예제 #5
0
    def get_mtu(self):
        """Return the current MTU value of this interface.

        This method will try to get the current MTU value, if fails will
        raise a NWException.
        """
        try:
            return self._get_interface_details().get('mtu')
        except (NWException, IndexError):
            raise NWException("Could not get MUT value.")
예제 #6
0
 def config_filename(self):
     current_distro = distro_detect()
     if current_distro.name in ['rhel', 'fedora']:
         path = "/etc/sysconfig/network-scripts"
     elif current_distro.name == 'SuSE':
         path = "/etc/sysconfig/network"
     else:
         msg = 'Distro not supported by API. Could not get interface filename.'
         raise NWException(msg)
     return "{}/ifcfg-{}".format(path, self.name)
예제 #7
0
 def _connect(self):
     session = Session(host=self.host,
                       port=self.port,
                       user=self.username,
                       key=self.key,
                       password=self.password)
     if session.connect():
         return session
     msg = f"Failed connecting {self.host}:{self.port}"
     raise NWException(msg)
예제 #8
0
 def config_filename(self):
     current_distro = distro_detect()
     if current_distro.name in ["rhel", "fedora"]:
         path = "/etc/sysconfig/network-scripts"
     elif current_distro.name == "SuSE":
         path = "/etc/sysconfig/network"
     else:
         msg = "Distro not supported by API. Could not get interface filename."
         raise NWException(msg)
     return f"{path}/ifcfg-{self.name}"
예제 #9
0
    def interfaces(self):
        cmd = 'ls /sys/class/net'
        try:
            names = run_command(cmd, self).split()
        except Exception as ex:
            raise NWException(f"Failed to get interfaces: {ex}")

        if "bonding_masters" in names:
            names.remove("bonding_masters")

        return [NetworkInterface(if_name=name, host=self) for name in names]
예제 #10
0
    def get_hwaddr(self):
        """Get the Hardware Address (MAC) of this interface.

        This method will try to get the address and if fails it will raise a
        NWException.
        """
        cmd = "cat /sys/class/net/{}/address".format(self.name)
        try:
            return run_command(cmd, self.host)
        except Exception as ex:
            raise NWException("Failed to get hw address: {}".format(ex))
예제 #11
0
    def bring_up(self):
        """"Wake-up the interface.

        This will wake-up the interface link.

        You must have sudo permissions to run this method on a host.
        """
        cmd = "ip link set {} up".format(self.name)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            raise NWException("Failed to bring up: %s" % ex)
예제 #12
0
    def remove_all_vlans(self):
        """Remove all VLANs of this interface.

        This method will remove all the VLAN interfaces associated by the
        interface. If it fails, the method will raise a NWException.
        """
        try:
            for v in self.vlans.values():
                cmd = "ip link delete {}".format(v)
                run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            raise NWException("Failed to remove VLAN interface: {}".format(ex))
예제 #13
0
    def is_admin_link_up(self):
        """Check the admin link state is up or not.

        :return: True or False, True if network interface state is 'UP'
                 otherwise will return False.
        """
        try:
            if 'UP' in self._get_interface_details().get('flags'):
                return True
        except (NWException, IndexError):
            raise NWException("Could not get Administrative link state.")
        return False
예제 #14
0
    def is_operational_link_up(self):
        """Check Operational link state is up or not.

        :return: True or False. True if operational link state is LOWER_UP,
                 otherwise will return False.
        """
        try:
            if 'LOWER_UP' in self._get_interface_details().get('flags'):
                return True
        except (NWException, IndexError):
            raise NWException("Could not get operational link state.")
        return False
예제 #15
0
    def get_default_route_interface(self):
        """Get a list of default routes interfaces

        :return: list of interface names
        """
        cmd = "ip -j route list default"
        output = run_command(cmd, self)
        try:
            result = json.loads(output)
            return [str(item['dev']) for item in result]
        except Exception as ex:
            raise NWException(f"could not get default route interface name:"
                              f" {ex}")
예제 #16
0
    def restore_from_backup(self):
        """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.
        """

        backup_file = "{}.backup".format(self.config_filename)
        if os.path.exists(backup_file):
            shutil.move(backup_file, self.config_filename)
        else:
            raise NWException(
                "Backup file not available, could not restore file.")
예제 #17
0
    def bring_down(self):
        """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.
        """

        cmd = "ip link set {} down".format(self.name)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            raise NWException("Failed to bring down: %s" % ex)
예제 #18
0
 def restore_slave_cfg_file(self):
     """
     Restore or delete slave config files.
     """
     if self.if_type != "Bond":
         return
     for slave_config in self.slave_config_filename:
         backup_slave_config = f"{slave_config}.backup"
         try:
             if os.path.exists(backup_slave_config):
                 shutil.move(backup_slave_config, slave_config)
             else:
                 os.remove(slave_config)
         except Exception as ex:
             raise NWException(f"Could not restore the config file {ex}")
예제 #19
0
    def set_hwaddr(self, 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.

        :param hwaddr: Hardware Address (Mac Address)
        """
        cmd = "ip link set dev {} address {}".format(self.name, hwaddr)
        try:
            run_command(cmd, self.self.host, sudo=True)
        except Exception as ex:
            raise NWException("Adding hw address fails: %s" % ex)
예제 #20
0
    def flush_ipaddr(self):
        """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.
        """
        cmd = f"ip addr flush dev {self.name}"
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            msg = f"Failed to flush ipaddr. {ex}"
            raise NWException(msg)
예제 #21
0
    def remove_link(self):
        """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.
        """
        cmd = 'ip link del dev {}'.format(self.name)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            msg = 'Failed to delete link. {}'.format(ex)
            raise NWException(msg)
예제 #22
0
 def restore_slave_cfg_file(self):
     """
     Restore or delete slave config files.
     """
     if self.if_type != 'Bond':
         return
     for slave_config in self.slave_config_filename:
         backup_slave_config = "{}.backup".format(slave_config)
         try:
             if os.path.exists(backup_slave_config):
                 shutil.move(backup_slave_config, slave_config)
             else:
                 os.remove(slave_config)
         except Exception as ex:
             raise NWException("Could not restore \
                               the config file {}".format(ex))
예제 #23
0
    def remove_ipaddr(self, 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.
        """
        ip = ip_interface(f"{ipaddr}/{netmask}")
        cmd = f"ip addr del {ip.compressed} dev {self.name}"
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            msg = f"Failed to remove ipaddr. {ex}"
            raise NWException(msg)
예제 #24
0
    def remove_ipaddr(self, 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.
        """
        ip = ip_interface("{}/{}".format(ipaddr, netmask))
        cmd = 'ip addr del {} dev {}'.format(ip.compressed, self.name)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            msg = 'Failed to remove ipaddr. {}'.format(ex)
            raise NWException(msg)
예제 #25
0
    def add_ipaddr(self, 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.

        :param ipaddr: IP Address
        :param netmask: Network mask
        """

        ip = ip_interface("{}/{}".format(ipaddr, netmask))
        cmd = 'ip addr add {} dev {}'.format(ip.compressed, self.name)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            raise NWException("Failed to add address {}".format(ex))
예제 #26
0
    def ping_check(self, 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.

        :param peer_ip: Peer IP address (IPv4 or IPv6)
        :param count: How many packets to send. Default is 2
        :param options: ping command options. Default is None
        """
        cmd = "ping -I {} {} -c {}".format(self.name, peer_ip, count)
        if options is not None:
            cmd = "{} {}".format(cmd, options)
        try:
            run_command(cmd, self.host)
        except Exception as ex:
            raise NWException("Failed to ping: {}".format(ex))
예제 #27
0
    def add_vlan_tag(self, 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.

        :param vlan_num: VLAN ID
        :param vlan_name: option to name VLAN interface, by default it is named
                          <interface_name>.<vlan_num>
        """

        vlan_name = vlan_name or "{}.{}".format(self.name, vlan_num)
        cmd = "ip link add link {} name {} type vlan id {}".format(
            self.name, vlan_name, vlan_num)
        try:
            run_command(cmd, self.host, sudo=True)
        except Exception as ex:
            raise NWException("Failed to add VLAN tag: {}".format(ex))
예제 #28
0
    def set_mtu(self, 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.

        :param mtu:  mtu size that need to be set. This must be an int.
        :param timeout: how many seconds to wait until the interface is
                        up again. Default is 30.
        """
        cmd = "ip link set %s mtu %s" % (self.name, mtu)
        run_command(cmd, self.host, sudo=True)
        wait_for(self.is_link_up, timeout=timeout)
        if int(mtu) != self.get_mtu():
            raise NWException("Failed to set MTU.")
예제 #29
0
    def remove_vlan_by_tag(self, 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.

        :param vlan_num: VLAN ID
        :return: True or False, True if it found the VLAN interface and removed
                 it successfully, otherwise it will return False.
        """
        if str(vlan_num) in self.vlans:
            vlan_name = self.vlans[str(vlan_num)]
        else:
            return False
        cmd = "ip link delete {}".format(vlan_name)

        try:
            run_command(cmd, self.host, sudo=True)
            return True
        except Exception as ex:
            raise NWException("Failed to remove VLAN interface: {}".format(ex))
예제 #30
0
    def get_ipaddrs(self, 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.

        :param version: Address Family Version (4 or 6). This must be a integer
                        and default is 4.
        :return: IP address as string.
        """
        if version not in [4, 6]:
            raise NWException("Version {} not supported".format(version))

        try:
            details = self._get_interface_details(version)
            addr_info = details.get('addr_info')
            if addr_info:
                return [x.get('local') for x in addr_info]
        except (NWException, IndexError):
            msg = "Could not get ip addresses for {}".format(self.name)
            LOG.debug(msg)
            return []