def deactivate_iface(self, ifacename): filename = ifcfg_filename_format % ifacename filepath = os.sep + network_configpath + filename wok_log.info('Deactivating an interface ' + ifacename) if os.path.exists(filepath): cmd_ifdown = ['ifdown', '%s' % ifacename] out, error, returncode = run_command(cmd_ifdown) if returncode != 0: raise OperationFailed('GINNET0017E', { 'name': encode_value(ifacename), 'error': encode_value(error) }) wok_log.info( 'Connection successfully deactivated for the interface ' + ifacename) wok_log.info('Bringing down an interface ' + ifacename) iface_type = netinfo.get_interface_type(ifacename) if iface_type == "nic": cmd_ipdown = ['ip', 'link', 'set', '%s' % ifacename, 'down'] out, error, returncode = run_command(cmd_ipdown) if returncode != 0: raise OperationFailed('GINNET0060E', { 'name': encode_value(ifacename), 'error': encode_value(error) }) # Some times based on system load, it takes few seconds to # reflect the /sys/class/net files upon execution of 'ip link # set' command. Following snippet is to wait util files get # reflect. timeout = self.wait_time(ifacename) if timeout == 5: wok_log.warn("Time-out has happened upon execution of 'ip " "link set <interface> down', hence behavior " "of activating an interface may not as " "expected.") else: wok_log.info('Successfully brought down the interface ' + ifacename) vlan_or_bond = [ nw_cfginterfaces_utils.IFACE_BOND, nw_cfginterfaces_utils.IFACE_VLAN ] if iface_type in vlan_or_bond: if encode_value(ifacename) in ethtool.get_devices(): cmd_ip_link_del = ['ip', 'link', 'delete', '%s' % ifacename] out, error, returncode = run_command(cmd_ip_link_del) if (returncode != 0 and (encode_value(ifacename) in ethtool.get_devices())): raise OperationFailed( 'GINNET0017E', { 'name': encode_value(ifacename), 'error': encode_value(error) })
def deactivate_iface(self, ifacename): wok_log.info('Deactivating an interface ' + ifacename) cmd_ifdown = ['ifdown', '%s' % ifacename] out, error, returncode = run_command(cmd_ifdown) if returncode != 0: wok_log.error( 'Unable to deactivate the interface on ' + ifacename + ', ' + error) raise OperationFailed('GINNET0017E', {'name': ifacename, 'error': error}) wok_log.info( 'Connection successfully deactivated for the interface ' + ifacename) wok_log.info('Bringing down an interface ' + ifacename) iface_type = netinfo.get_interface_type(ifacename) if iface_type == "Ethernet": cmd_ipdown = ['ip', 'link', 'set', '%s' % ifacename, 'down'] out, error, returncode = run_command(cmd_ipdown) if returncode != 0: wok_log.error( 'Unable to bring down the interface on ' + ifacename + ', ' + error) raise OperationFailed('GINNET0060E', {'name': ifacename, 'error': error}) # Some times based on system load, it takes few seconds to # reflect the /sys/class/net files upon execution of 'ip link # set' command. Following snippet is to wait util files get # reflect. timeout = self.wait_time(ifacename) if timeout == 5: wok_log.warn("Time-out has happened upon execution of 'ip " "link set <interface> down', hence behavior of " "activating an interface may not as expected.") else: wok_log.info('Successfully brought down the interface ' + ifacename) vlan_or_bond = [nw_cfginterfaces_utils.IFACE_BOND, nw_cfginterfaces_utils.IFACE_VLAN] if iface_type in vlan_or_bond: if ifacename in ethtool.get_devices(): cmd_ip_link_del = ['ip', 'link', 'delete', '%s' % ifacename] out, error, returncode = run_command(cmd_ip_link_del) if returncode != 0 and ifacename in ethtool.get_devices(): wok_log.error('Unable to delete the interface ' + ifacename + ', ' + error) raise OperationFailed('GINNET0017E', {'name': ifacename, 'error': error})
def run_cmd_noargs(cmd, args): if args: run_cmd(cmd, args[0], None) else: global all_devices all_devices = ethtool.get_devices() run_cmd(cmd, None, None)
def lookup(self, name): if encode_value(name) not in map(encode_value, ethtool.get_devices()): raise NotFoundError('KCHIFACE0001E', {'name': name}) ipaddr = '' netmask = '' module = 'unknown' status = 'down' try: ipaddr = ethtool.get_ipaddr(encode_value(name)) netmask = ethtool.get_netmask(encode_value(name)) module = ethtool.get_module(encode_value(name)) flags = ethtool.get_flags(encode_value(name)) status = 'up' if flags & (ethtool.IFF_RUNNING | ethtool.IFF_UP) else 'down' except IOError: pass iface_type = netinfo.get_interface_type(name) return { 'name': name, 'type': iface_type, 'status': status, 'ipaddr': ipaddr, 'netmask': netmask, 'module': module, }
def linux(self): nic_dict = {} i = 1 # Get info about all devices devices = ethtool.get_interfaces_info(ethtool.get_devices()) # Retrieve and print info for dev in devices: name = dev.device mac = dev.mac_address ip = dev.ipv4_address netmask = dev.ipv4_netmask num = str(i) if name != 'lo' and ip is not None: temp = { num: { 'name': name, 'mac': mac, 'ip': ip, 'netmask': netmask } } nic_dict = dict(nic_dict, **temp) i += 1 nic_dict = dict(nic=nic_dict) return nic_dict
def all_interfaces(): """ This interface will return all the interfaces as seen by the ethtool. This is equivalent to cat /proc/net/dev or ip addr show :return: """ return ethtool.get_devices()
def _getIPAddress(self): address = None stdout = '' if ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() ): self.logger.debug('Acquiring bridge address') rc, stdout, stderr = self.execute( args=( self.command.get('ip'), 'addr', 'show', self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME], ), ) else: self.logger.debug('Acquiring nic address') rc, stdout, stderr = self.execute( args=( self.command.get('ip'), 'addr', 'show', self.environment[ohostedcons.NetworkEnv.BRIDGE_IF], ), ) for line in stdout: addressmatch = self._ADDRESS_RE.match(line) if addressmatch is not None: address = addressmatch.group('address') break if address is None: raise RuntimeError(_('Cannot acquire bridge address')) self.logger.debug(address) return address
def lookup(self, name): if encode_value(name) not in map(encode_value, ethtool.get_devices()): raise NotFoundError("KCHIFACE0001E", {'name': name}) ipaddr = '' netmask = '' module = 'unknown' status = 'down' try: ipaddr = ethtool.get_ipaddr(encode_value(name)) netmask = ethtool.get_netmask(encode_value(name)) module = ethtool.get_module(encode_value(name)) flags = ethtool.get_flags(encode_value(name)) status = 'up' if flags & (ethtool.IFF_RUNNING | ethtool.IFF_UP) \ else 'down' except IOError: pass iface_type = netinfo.get_interface_type(name) return {'name': name, 'type': iface_type, 'status': status, 'ipaddr': ipaddr, 'netmask': netmask, 'module': module}
def getLinkedInterfaces(liveDVD=True): """ Return a list of all network interfaces on the system with active link (the same as ethtool.get_active_devices(), however, it also works when the system is booted via liveDVD and the network must be started manually - Network.startLiveDVDNetwork()) @type mountDir: boolean @param mountDir: True is running in liveDVD @rtype: array @returns: list of NIC with active link """ interfaces = [] devices = ethtool.get_devices() for dev in devices: cmd = ['ethtool', dev] proc = Popen(cmd, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode != 0: raise Exception("NETWORK: Failed to execute ethtool on %s (exit code = %s):\n%s" % (dev, proc.returncode, err)) if out.rstrip().endswith("Link detected: yes"): if liveDVD: device = Network.getUdevPredictableName(dev) else: device = dev interfaces.append(device) return interfaces
def get_network_info(): interfaces = {} # get names inames = ethtool.get_devices() for iname in inames: mac = ethtool.get_hwaddr(iname) if mac == "00:00:00:00:00:00": mac = "?" try: ip = ethtool.get_ipaddr(iname) if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: nm = ethtool.get_netmask(iname) except: nm = "?" interfaces[iname] = {"ip_address": ip, "mac_address": mac, "netmask": nm, "bridge": bridge, "module": module} # print interfaces return interfaces
def _getMyIPAddress(self): device = (self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] if self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() else self.environment[ohostedcons.NetworkEnv.BRIDGE_IF]) self.logger.debug("Acquiring '{device}' address".format( device=device, )) rc, stdout, stderr = self.execute(args=( self.command.get('ip'), 'addr', 'show', device, ), ) for line in stdout: addressmatch = self._INET_ADDRESS_RE.match(line) if addressmatch is not None: address = addressmatch.group('address') break self.logger.debug('address: ' + str(address)) if address is None: raise RuntimeError(_('Cannot acquire nic/bridge address')) try: ipna = netaddr.IPNetwork(address) except netaddr.AddrFormatError: raise RuntimeError(_('Cannot acquire a valid nic/bridge address')) return ipna
def get_network_info(): try: import ethtool except: raise InfoException("the python-ethtool module is required to use this feature (is your OS>=EL3?)") interfaces = {} # get names inames = ethtool.get_devices() for iname in inames: mac = ethtool.get_hwaddr(iname) if mac == "00:00:00:00:00:00": mac = "?" try: ip = ethtool.get_ipaddr(iname) if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: nm = ethtool.get_netmask(iname) except: nm = "?" interfaces[iname] = {"ip_address": ip, "mac_address": mac, "netmask": nm, "bridge": bridge, "module": module} # print interfaces return interfaces
def lookup(self, name): """ Populate info using runtime information from /sys/class/net files for active interfaces and for inactive bond and vlan interfaces from cfg files :param name: :return: """ try: if name in ethtool.get_devices(): info = netinfo.get_interface_info(name) return info elif cfginterfaces.is_cfgfileexist(name): type = cfginterfaces.get_type(name).lower() if type in [cfginterfaces.IFACE_BOND, cfginterfaces.IFACE_VLAN]: raise ValueError device = cfginterfaces.get_device(name) info = {'device': device, 'type': cfginterfaces.get_type(name), 'status': "down", 'ipaddr': "", 'netmask': "", 'macaddr': ""} return info else: raise ValueError('unknown interface: %s' % name) except ValueError: raise NotFoundError("GINNET0014E", {'name': name})
def _detect_bridges(self): if (self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices()): self.logger.info( _('Bridge {bridge} already created').format( bridge=self.environment[ ohostedcons.NetworkEnv.BRIDGE_NAME]))
def deactivate_iface(self, ifacename): filename = ifcfg_filename_format % ifacename filepath = os.sep + network_configpath + filename wok_log.info('Deactivating an interface ' + ifacename) if os.path.exists(filepath): cmd_ifdown = ['ifdown', '%s' % ifacename] out, error, returncode = run_command(cmd_ifdown) if returncode != 0: raise OperationFailed('GINNET0017E', {'name': encode_value(ifacename), 'error': encode_value(error)}) wok_log.info( 'Connection successfully deactivated for the interface ' + ifacename) wok_log.info('Bringing down an interface ' + ifacename) iface_type = netinfo.get_interface_type(ifacename) if iface_type == "nic": cmd_ipdown = ['ip', 'link', 'set', '%s' % ifacename, 'down'] out, error, returncode = run_command(cmd_ipdown) if returncode != 0: raise OperationFailed('GINNET0060E', {'name': encode_value(ifacename), 'error': encode_value(error)}) # Some times based on system load, it takes few seconds to # reflect the /sys/class/net files upon execution of 'ip link # set' command. Following snippet is to wait util files get # reflect. timeout = self.wait_time(ifacename) if timeout == 5: wok_log.warn("Time-out has happened upon execution of 'ip " "link set <interface> down', hence behavior " "of activating an interface may not as " "expected.") else: wok_log.info('Successfully brought down the interface ' + ifacename) vlan_or_bond = [nw_cfginterfaces_utils.IFACE_BOND, nw_cfginterfaces_utils.IFACE_VLAN] if iface_type in vlan_or_bond: if encode_value(ifacename) in ethtool.get_devices(): cmd_ip_link_del = ['ip', 'link', 'delete', '%s' % ifacename] out, error, returncode = run_command(cmd_ip_link_del) if (returncode != 0 and (encode_value(ifacename) in ethtool.get_devices())): raise OperationFailed('GINNET0017E', {'name': encode_value(ifacename), 'error': encode_value(error)})
def _getMyIPAddrList(self): device = ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] if self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() else self.environment[ohostedcons.NetworkEnv.BRIDGE_IF] ) self.logger.debug( "Acquiring '{device}' address".format( device=device, ) ) rc, stdout, stderr = self.execute( args=( self.command.get('ip'), 'addr', 'show', device, 'scope', 'global' ), ) alist = [] addressmatchs4list = ( re.findall(self.IPv4RE, '\n'.join(stdout)) if not self.environment[ ohostedcons.NetworkEnv.FORCE_IPV6 ] else [] ) addressmatchs6list = ( re.findall(self.IPv6RE, '\n'.join(stdout)) if not self.environment[ ohostedcons.NetworkEnv.FORCE_IPV4 ] else [] ) for amatch in (addressmatchs6list + addressmatchs4list): addr = '{a}/{pl}'.format( a=amatch[0], pl=amatch[1], ) self.logger.debug('address: {a}'.format(a=addr)) try: ipna = netaddr.IPNetwork(addr) alist.append(ipna) except netaddr.AddrFormatError: self.logger.error( _('Invalid nic/bridge address: {a}').format(a=addr) ) if not alist: raise RuntimeError( _('Cannot acquire nic/bridge address') ) return alist
def get_auto_pf(self, fabric_type): ifcs = ethtool.get_devices() pfs = filter(self.verify_vendor_pf, ifcs) pfs = filter(self.is_sriov_pf, pfs) pfs = self.filter_ifcs_module(pfs, fabric_type) if len(pfs) != 1: LOG.error("Multiple PFs found %s.Configure Manually." % pfs) sys.exit(1) return pfs[0]
def get_network_info(): try: # python 2 import ethtool ethtool_available = True except ImportError: # python 3 import netifaces ethtool_available = False interfaces = {} # get names if ethtool_available: inames = ethtool.get_devices() else: inames = netifaces.interfaces() for iname in inames: if ethtool_available: mac = ethtool.get_hwaddr(iname) else: mac = netifaces.ifaddresses(iname)[netifaces.AF_LINK][0]['addr'] if mac == "00:00:00:00:00:00": mac = "?" try: if ethtool_available: ip = ethtool.get_ipaddr(iname) else: ip = netifaces.ifaddresses(iname)[netifaces.AF_INET][0]['addr'] if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: if ethtool_available: nm = ethtool.get_netmask(iname) else: nm = netifaces.ifaddresses(iname)[netifaces.AF_INET][0]['netmask'] except: nm = "?" interfaces[iname] = { "ip_address" : ip, "mac_address" : mac, "netmask" : nm, "bridge" : bridge, "module" : module } # print(interfaces) return interfaces
def get_all_interfaces(): import ethtool # Not sure how robust this will be; need to test with real gear. # In theory, should do the job to exclude IPoIB and lo interfaces. hwaddr_blacklist = ['00:00:00:00:00:00', '80:00:00:48:fe:80'] eth_interfaces = [] for device in ethtool.get_devices(): if ethtool.get_hwaddr(device) not in hwaddr_blacklist: eth_interfaces.append(CorosyncRingInterface(device)) return eth_interfaces
def GetInterfaceList(): all_interfaces = ethtool.get_devices() if 'lo' in all_interfaces: all_interfaces.remove('lo') for i in all_interfaces: filename = GetInterfaceConfigFileName(i) if not os.access(filename, os.R_OK): all_interfaces.remove(i) return all_interfaces
def etconfig(): ifaces = {} for i in ethtool.get_devices(): ifo = [] for k in (ethtool.get_ipaddr,ethtool.get_netmask,ethtool.get_hwaddr): try: ifo.append(k(i)) except: ifo.append('') ifaces[i] = {'addr': ifo[0], 'netmask': ifo[1], 'hwaddr': ifo[2]} return ifaces
def _detect_bridges(self): if ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() ): self.logger.info( _( 'Bridge {bridge} already created' ).format( bridge=self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] ) )
def list_eth_ips(): devcfgs = ethtool.get_interfaces_info(ethtool.get_devices()) addrs = set() for d in devcfgs: if d.ipv4_address: addrs.add(d.ipv4_address) addrs.add("0.0.0.0") for ip6 in d.get_ipv6_addresses(): addrs.add(ip6.address) addrs.add("::0") # only list ::0 if ipv6 present return sorted(addrs)
def MakeReport(self): ncfg_n = libxml2.newNode("NetworkConfig") (defgw4, defgw6) = self.net_GetDefaultGW() # Make an interface tag for each device found if hasattr(ethtool, 'get_interfaces_info'): # Using the newer python-ethtool API (version >= 0.4) for dev in ethtool.get_interfaces_info(ethtool.get_devices()): if cmp(dev.device, 'lo') == 0: continue intf_n = libxml2.newNode('interface') intf_n.newProp('device', dev.device) intf_n.newProp('hwaddr', dev.mac_address) ncfg_n.addChild(intf_n) # Protcol configurations if dev.ipv4_address: ipv4_n = libxml2.newNode('IPv4') ipv4_n.newProp('ipaddr', dev.ipv4_address) ipv4_n.newProp('netmask', str(dev.ipv4_netmask)) ipv4_n.newProp('broadcast', dev.ipv4_broadcast) ipv4_n.newProp('defaultgw', (defgw4 == dev.device) and '1' or '0') intf_n.addChild(ipv4_n) for ip6 in dev.get_ipv6_addresses(): ipv6_n = libxml2.newNode('IPv6') ipv6_n.newProp('ipaddr', ip6.address) ipv6_n.newProp('netmask', str(ip6.netmask)) ipv6_n.newProp('scope', ip6.scope) intf_n.addChild(ipv6_n) else: # Fall back to older python-ethtool API (version < 0.4) ifdevs = ethtool.get_active_devices() ifdevs.remove('lo') ifdevs.sort() for dev in ifdevs: intf_n = libxml2.newNode('interface') intf_n.newProp('device', dev.device) intf_n.newProp('hwaddr', dev.mac_address) ncfg_n.addChild(intf_n) ipv4_n = libxml2.newNode('IPv4') ipv4_n.newProp('ipaddr', ethtool.get_ipaddr(dev)) ipv4_n.newProp('netmask', str(ethtool.get_netmask(dev))) ipv4_n.newProp('defaultgw', (defgw4 == dev) and '1' or '0') intf_n.addChild(ipv4_n) return ncfg_n
def get_interface_info(iface): """Returns information about the interface iface. Args: iface (str): the interface name. Returns: dict: a dict containing the interface info. Format: { 'device': (str), 'name': (str), 'type': (str), 'status': (str), 'link_detected': (str), 'ipaddr': (str), 'netmask': (str), 'macaddr': (str), 'module': (str), 'nic_type': (str) } """ if encode_value(iface) not in map(encode_value, ethtool.get_devices()): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(encode_value(iface)) netmask = ethtool.get_netmask(encode_value(iface)) except IOError: pass kernel_module = get_interface_kernel_module(iface) iface_type = get_interface_type(iface) nic_type = 'N/A' if iface_type != 'nic' else get_nic_type( iface, kernel_module) return { 'device': iface, 'name': iface, 'type': iface_type, 'status': operstate(iface), 'link_detected': link_detected(iface), 'ipaddr': ipaddr, 'netmask': netmask, 'macaddr': macaddr(iface), 'module': kernel_module, 'nic_type': nic_type }
def MakeReport(self): ncfg_n = libxml2.newNode("NetworkConfig") (defgw4, defgw6) = self.net_GetDefaultGW() # Make an interface tag for each device found if hasattr(ethtool, 'get_interfaces_info'): # Using the newer python-ethtool API (version >= 0.4) for dev in ethtool.get_interfaces_info(ethtool.get_devices()): if cmp(dev.device,'lo') == 0: continue intf_n = libxml2.newNode('interface') intf_n.newProp('device', dev.device) intf_n.newProp('hwaddr', dev.mac_address) ncfg_n.addChild(intf_n) # Protcol configurations if dev.ipv4_address: ipv4_n = libxml2.newNode('IPv4') ipv4_n.newProp('ipaddr', dev.ipv4_address) ipv4_n.newProp('netmask', str(dev.ipv4_netmask)) ipv4_n.newProp('broadcast', dev.ipv4_broadcast) ipv4_n.newProp('defaultgw', (defgw4 == dev.device) and '1' or '0') intf_n.addChild(ipv4_n) for ip6 in dev.get_ipv6_addresses(): ipv6_n = libxml2.newNode('IPv6') ipv6_n.newProp('ipaddr', ip6.address) ipv6_n.newProp('netmask', str(ip6.netmask)) ipv6_n.newProp('scope', ip6.scope) intf_n.addChild(ipv6_n) else: # Fall back to older python-ethtool API (version < 0.4) ifdevs = ethtool.get_active_devices() ifdevs.remove('lo') ifdevs.sort() for dev in ifdevs: intf_n = libxml2.newNode('interface') intf_n.newProp('device', dev.device) intf_n.newProp('hwaddr', dev.mac_address) ncfg_n.addChild(intf_n) ipv4_n = libxml2.newNode('IPv4') ipv4_n.newProp('ipaddr', ethtool.get_ipaddr(dev)) ipv4_n.newProp('netmask', str(ethtool.get_netmask(dev))) ipv4_n.newProp('defaultgw', (defgw4 == dev) and '1' or '0') intf_n.addChild(ipv4_n) return ncfg_n
def _setup(self): if ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() ): self.logger.info( _( 'Bridge {bridge} already created' ).format( bridge=self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] ) ) self._enabled = False self._hostname_helper = osetuphostname.Hostname(plugin=self)
def _setup(self): if ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() ): self.logger.info( _( 'Bridge {bridge} already created' ).format( bridge=self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] ) ) self._enabled = False else: self.command.detect('vdsClient')
def list_eth_ips(): if not ethtool: return [] devcfgs = ethtool.get_interfaces_info(ethtool.get_devices()) addrs = set() for d in devcfgs: if d.ipv4_address: addrs.add(d.ipv4_address) addrs.add("0.0.0.0") for ip6 in d.get_ipv6_addresses(): addrs.add(ip6.address) addrs.add("::0") # only list ::0 if ipv6 present return sorted(addrs)
def get_network_info(): interfaces = {} # get names if ethtool_available: inames = ethtool.get_devices() else: inames = netifaces.interfaces() for iname in inames: if ethtool_available: mac = ethtool.get_hwaddr(iname) else: mac = netifaces.ifaddresses(iname)[netifaces.AF_LINK][0]['addr'] if mac == "00:00:00:00:00:00": mac = "?" try: if ethtool_available: ip = ethtool.get_ipaddr(iname) else: ip = netifaces.ifaddresses(iname)[netifaces.AF_INET][0]['addr'] if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: if ethtool_available: nm = ethtool.get_netmask(iname) else: nm = netifaces.ifaddresses(iname)[netifaces.AF_INET][0]['netmask'] except: nm = "?" interfaces[iname] = { "ip_address": ip, "mac_address": mac, "netmask": nm, "bridge": bridge, "module": module } # print interfaces return interfaces
def get_interface_info(iface): """Returns information about the interface iface. Args: iface (str): the interface name. Returns: dict: a dict containing the interface info. Format: { 'device': (str), 'name': (str), 'type': (str), 'status': (str), 'link_detected': (str), 'ipaddr': (str), 'netmask': (str), 'macaddr': (str), 'module': (str), 'nic_type': (str) } """ if encode_value(iface) not in map(encode_value, ethtool.get_devices()): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(encode_value(iface)) netmask = ethtool.get_netmask(encode_value(iface)) except IOError: pass kernel_module = get_interface_kernel_module(iface) iface_type = get_interface_type(iface) nic_type = 'N/A' if iface_type is not 'nic' \ else get_nic_type(iface, kernel_module) return {'device': iface, 'name': iface, 'type': iface_type, 'status': operstate(iface), 'link_detected': link_detected(iface), 'ipaddr': ipaddr, 'netmask': netmask, 'macaddr': macaddr(iface), 'module': kernel_module, 'nic_type': nic_type}
def _get_ipv4_addr_list(self): """ When DNS record is not configured properly for the system, then try to get list of all IPv4 addresses from all devices. Return 127.0.0.1 only in situation when there is only loopback device. :return: list of IPv4 addresses """ addr_list = [] interface_info = ethtool.get_interfaces_info(ethtool.get_devices()) for info in interface_info: for addr in info.get_ipv4_addresses(): if addr.address != '127.0.0.1': addr_list.append(addr.address) if len(addr_list) == 0: addr_list = ['127.0.0.1'] return addr_list
def _get_ipv6_addr_list(self): """ When DNS record is not configured properly for the system, then try to get list of all IPv6 addresses from all devices. Return ::1 only in situation when there no device with valid global IPv6 address. :return: list of IPv6 addresses """ addr_list = [] interface_info = ethtool.get_interfaces_info(ethtool.get_devices()) for info in interface_info: for addr in info.get_ipv6_addresses(): if addr.scope == 'universe': addr_list.append(addr.address) if len(addr_list) == 0: addr_list = ['::1'] return addr_list
def get_network_info(): try: import ethtool except: try: import rhpl.ethtool ethtool = rhpl.ethtool except: raise InfoException( "the rhpl or ethtool module is required to use this feature (is your OS>=EL3?)" ) interfaces = {} # get names inames = ethtool.get_devices() for iname in inames: mac = ethtool.get_hwaddr(iname) if mac == "00:00:00:00:00:00": mac = "?" try: ip = ethtool.get_ipaddr(iname) if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: nm = ethtool.get_netmask(iname) except: nm = "?" interfaces[iname] = { "ip_address": ip, "mac_address": mac, "netmask": nm, "bridge": bridge, "module": module } # print interfaces return interfaces
def get_interface_info(iface): if not iface in ethtool.get_devices(): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(iface) netmask = ethtool.get_netmask(iface) except IOError: pass return {'name': iface, 'type': get_interface_type(iface), 'status': 'active' if operstate(iface) == 'up' else 'inactive', 'ipaddr': ipaddr, 'netmask': netmask}
def get_interface_info(iface): if iface not in ethtool.get_devices(): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(iface) netmask = ethtool.get_netmask(iface) except IOError: pass return {'device': iface, 'type': get_interface_type(iface), 'status': link_detected(iface), 'ipaddr': ipaddr, 'netmask': netmask, 'macaddr': macaddr(iface)}
def _delTarget(network, parent, target): fs = list(filters(network, parent)) if fs: filt = fs[0] else: return [] devices = set(ethtool.get_devices()) acts = [act for act in filt.actions if act.target in devices and act.target != target] if acts: filt = Filter(prio=filt.prio, handle=filt.handle, actions=acts) filter_replace(network, parent, filt) else: filter_del(network, target, parent, filt.prio) return acts
def _getMyIPAddrList(self): device = ( self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] if self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME] in ethtool.get_devices() else self.environment[ohostedcons.NetworkEnv.BRIDGE_IF] ) self.logger.debug( "Acquiring '{device}' address".format( device=device, ) ) rc, stdout, stderr = self.execute( args=( self.command.get('ip'), 'addr', 'show', device, ), ) alist = [] addressmatchs4list = re.findall(self.IPv4RE, '\n'.join(stdout)) addressmatchs6list = re.findall(self.IPv6RE, '\n'.join(stdout)) for amatch in (addressmatchs4list + addressmatchs6list): addr = '{a}/{pl}'.format( a=amatch[0], pl=amatch[1], ) self.logger.debug('address: {a}'.format(a=addr)) try: ipna = netaddr.IPNetwork(addr) alist.append(ipna) except netaddr.AddrFormatError: self.logger.error( _('Invalid nic/bridge address: {a}').format(a=addr) ) if not alist: raise RuntimeError( _('Cannot acquire nic/bridge address') ) return alist
def get_interface_info(iface): if not iface in ethtool.get_devices(): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(iface) netmask = ethtool.get_netmask(iface) except IOError: pass return { 'name': iface, 'type': get_interface_type(iface), 'status': 'active' if operstate(iface) == 'up' else 'inactive', 'ipaddr': ipaddr, 'netmask': netmask }
def _delTarget(network, parent, target): fs = list(filters(network, parent)) if fs: filt = fs[0] else: return [] devices = set(ethtool.get_devices()) acts = [ act for act in filt.actions if act.target in devices and act.target != target ] if acts: filt = Filter(prio=filt.prio, handle=filt.handle, actions=acts) filter_replace(network, parent, filt) else: filter_del(network, target, parent, filt.prio) return acts
def getNetworkInterfaces(self): netinfdict = {} metakeys = [ 'mac_address', 'ipv4_address', 'ipv4_netmask', 'ipv4_broadcast' ] ipv6_metakeys = ['address', 'netmask'] try: for info in ethtool.get_interfaces_info(ethtool.get_devices()): for addr in info.get_ipv6_addresses(): for mkey in ipv6_metakeys: # ethtool returns a different scope for "public" IPv6 addresses # on different versions of RHEL. EL5 is "global", while EL6 is # "universe". Make them consistent. scope = addr.scope if scope == 'universe': scope = 'global' key = '.'.join([ 'net.interface', info.device, 'ipv6_%s' % (mkey), scope ]) attr = getattr(addr, mkey) if attr: netinfdict[key] = attr else: netinfdict[key] = "Unknown" # XXX: The kernel supports multiple IPv4 addresses on a single # interface when using iproute2. However, the ethtool.etherinfo.ipv4_* # members will only return the last retrieved IPv4 configuration. As # of 25 Jan 2012 work on a patch was in progress. See BZ 759150. for mkey in metakeys: key = '.'.join(['net.interface', info.device, mkey]) attr = getattr(info, mkey) if attr: netinfdict[key] = attr else: netinfdict[key] = "Unknown" except: print _( "Error reading network interface information:"), sys.exc_type self.allhw.update(netinfdict) return netinfdict
def lookup(self, name): """ Populate info using runtime information from /sys/class/net files for active interfaces and for inactive bond and vlan interfaces from cfg files :param name: :return: """ def get_actions_info_without_method(kernel_mod): info = self.actions_mod.get(kernel_mod, {}) for action in info.keys(): action_info = info[action] action_info.pop('method') info[action] = action_info return info try: if name in ethtool.get_devices(): info = netinfo.get_interface_info(name) elif cfginterfaces.is_cfgfileexist(name): type = cfginterfaces.get_type(name).lower() if type in [cfginterfaces.IFACE_BOND, cfginterfaces.IFACE_VLAN]: raise ValueError device = cfginterfaces.get_device(name) info = {'device': device, 'type': cfginterfaces.get_type(name), 'status': "down", 'ipaddr': "", 'netmask': "", 'macaddr': "", 'module': netinfo.get_interface_kernel_module(name)} else: raise ValueError('unknown interface: %s' % name) info['actions'] = get_actions_info_without_method(info['module']) return info except ValueError: raise NotFoundError("GINNET0014E", {'name': name})
def validate_bond_for_vlan(self, parent_iface): """ method to validate in the case of VLANs over bonds, it is important that the bond has slaves and that they are up, and vlan can not be configured over bond with the fail_over_mac=follow option. :param parent_iface: """ if parent_iface in ethtool.get_devices(): try: with open(FAIL_OVER_MAC % parent_iface) as dev_file: fail_over_mac = dev_file.readline().strip() except IOError: fail_over_mac = "n/a" if fail_over_mac == "follow 2": raise OperationFailed("GINNET0046E") else: """TODO: Need an investigation on, if parent of type bond is not active whether we can still create vlan interface or not. If 'yes', then can include code to validate the fail_over_mac in ifcfg persistant file""" wok_log.error("Parent interface of type 'Bond' is not active") raise OperationFailed("GINNET0051E") cfgdata = CfginterfaceModel().get_cfginterface_info(parent_iface) cfgInterfacesHelper.validate_dict_bond_for_vlan(cfgdata) slave_list = cfgdata[BASIC_INFO][BONDINFO][SLAVES] if len(slave_list) != 0: active_slave_found = True for slave in slave_list: # Fix ginger issue #144 if netinfo.operstate(slave) == STATE_DOWN: active_slave_found = False else: active_slave_found = True wok_log.info("One active slave okis found:" + slave) break if (not active_slave_found): raise OperationFailed("GINNET0047E") else: wok_log.error("Minimum one slave has to be given for the bond") raise OperationFailed("GINNET0037E") return
def lookup(self, name): """ Populate info using runtime information from /sys/class/net files for active interfaces and for inactive bond and vlan interfaces from cfg files :param name: :return: """ try: # encode name to ensure comparison are in same type. if encode_value(name) in ethtool.get_devices(): info = netinfo.get_interface_info(name) elif cfgInterfacesHelper.is_cfgfileexist(name): type = cfgInterfacesHelper.get_type(name).lower() if type not in IFACE_BOND + [IFACE_VLAN]: raise ValueError device = cfgInterfacesHelper.get_device(name) info = { 'device': device, 'type': cfgInterfacesHelper.get_type(name), 'status': "down", 'ipaddr': "", 'netmask': "", 'macaddr': "", 'module': netinfo.get_interface_kernel_module(name) } if info.get('type') is not 'nic': info['nic_type'] = 'N/A' else: info['nic_type'] = netinfo.get_nic_type(device) else: raise ValueError('unknown interface: %s' % name) info['rdma_enabled'] = netinfo.is_rdma_enabled(name) return info except ValueError: raise NotFoundError("GINNET0014E", {'name': name})
def list_eth_ips(ifnames=None): ''' List the IPv4 and IPv6 non-loopback, non link-local addresses (in the RFC3330 sense, not addresses attached to lo) of a list of ethernet interfaces from the SIOCGIFADDR struct. If ifname is omitted, list all IPs of all ifaces excepted for lo. ''' if ifnames is None: ifnames = [name for name in ethtool.get_devices() if name != 'lo'] devcfgs = ethtool.get_interfaces_info(ifnames) addrs = [] for d in devcfgs: if d.ipv4_address: addrs.append(d.ipv4_address) # For IPv6 addresses, we might have more of them on the same device, # and only grab global (universe) addresses. for ip6 in [a for a in d.get_ipv6_addresses() if a.scope == 'universe']: addrs.append(ip6.address) return sorted(set(addrs))
def getAvailableInterfaces(liveDVD=True): """ Returns all the network interfaces (eth/en[pP]) available on the system @type liveDVD: boolean @param liveDVD: True is running in liveDVD @rtype: dict @returns: (key = ethernet interface / value = mac addresss) available """ interfaces = {} devices = ethtool.get_devices() virtualIfaces = Network.getVirtualNic() for dev in devices: if dev not in virtualIfaces: if liveDVD: device = Network.getUdevPredictableName(dev) else: device = dev interfaces[device] = ethtool.get_hwaddr(dev) return interfaces
def get_interface_info(iface): if iface not in ethtool.get_devices(): raise ValueError('unknown interface: %s' % iface) ipaddr = '' netmask = '' try: ipaddr = ethtool.get_ipaddr(iface) netmask = ethtool.get_netmask(iface) except IOError: pass iface_link_detected = link_detected(iface) iface_status = 'active' if iface_link_detected != "n/a" else "inactive" return {'name': iface, 'type': get_interface_type(iface), 'status': iface_status, 'link_detected': iface_link_detected, 'ipaddr': ipaddr, 'netmask': netmask}
def validate_bond_for_vlan(self, parent_iface): """ method to validate in the case of VLANs over bonds, it is important that the bond has slaves and that they are up, and vlan can not be configured over bond with the fail_over_mac=follow option. :param parent_iface: """ if encode_value(parent_iface) in ethtool.get_devices(): try: with open(FAIL_OVER_MAC % parent_iface) as dev_file: fail_over_mac = dev_file.readline().strip() except IOError: fail_over_mac = "n/a" if fail_over_mac == "follow 2": raise OperationFailed("GINNET0046E") else: """TODO: Need an investigation on, if parent of type bond is not active whether we can still create vlan interface or not. If 'yes', then can include code to validate the fail_over_mac in ifcfg persistant file""" raise OperationFailed("GINNET0051E") cfgdata = CfginterfaceModel().get_cfginterface_info(parent_iface) cfgInterfacesHelper.validate_dict_bond_for_vlan(cfgdata) slave_list = cfgdata[BASIC_INFO][BONDINFO][SLAVES] if len(slave_list) != 0: active_slave_found = True for slave in slave_list: # Fix ginger issue #144 if netinfo.operstate(slave) == STATE_DOWN: active_slave_found = False else: active_slave_found = True wok_log.info("One active slave is found:" + slave) break if (not active_slave_found): raise OperationFailed("GINNET0047E") else: raise OperationFailed("GINNET0037E") return
def get_auto_pf(self, fabric_type): def log_error_and_exit(err_msg): LOG.error(err_msg) sys.exit(1) mlnx_pfs = [ ifc for ifc in ethtool.get_devices() if self.verify_vendor_pf(ifc) ] if not mlnx_pfs: log_error_and_exit("Didn't find any Mellanox devices.") mlnx_pfs = [ifc for ifc in mlnx_pfs if self.is_sriov_pf(ifc)] if not mlnx_pfs: log_error_and_exit("Didn't find Mellanox NIC " "with SR-IOV capabilities.") mlnx_pfs = self.filter_ifcs_module(mlnx_pfs, fabric_type) if not mlnx_pfs: log_error_and_exit("Didn't find Mellanox NIC of type %s with " "SR-IOV capabilites." % fabric_type) if len(mlnx_pfs) != 1: log_error_and_exit("Found multiple PFs %s. Configure Manually." % mlnx_pfs) return mlnx_pfs[0]
def get_network_info(): interfaces = {} # get names inames = ethtool.get_devices() for iname in inames: mac = ethtool.get_hwaddr(iname) if mac == "00:00:00:00:00:00": mac = "?" try: ip = ethtool.get_ipaddr(iname) if ip == "127.0.0.1": ip = "?" except: ip = "?" bridge = 0 module = "" try: nm = ethtool.get_netmask(iname) except: nm = "?" interfaces[iname] = { "ip_address": ip, "mac_address": mac, "netmask": nm, "bridge": bridge, "module": module } # print interfaces return interfaces
def get_dev_netaddrs(): nets = [] for dev in ethtool.get_devices(): devnet = get_dev_netaddr(dev) devnet and nets.append(ipaddr.IPNetwork(devnet)) return nets
usage() return elif o in ("-c", "--show-coalesce"): run_cmd_noargs(show_coalesce, args) break elif o in ("-i", "--driver"): run_cmd_noargs(show_driver, args) break elif o in ("-k", "--show-offload"): run_cmd_noargs(show_offload, args) break elif o in ("-g", "--show-ring"): run_cmd_noargs(show_ring, args) break elif o in ("-K", "--offload", "-C", "--coalesce", "-G", "--set-ring"): all_devices = ethtool.get_devices() if len(args) < 2: usage() sys.exit(1) if args[0] not in all_devices: interface = None else: interface = args[0] args = args[1:] if o in ("-K", "--offload"): cmd = set_offload elif o in ("-C", "--coalesce"): cmd = set_coalesce elif o in ("-G", "--set-ring"):
def read_network_interfaces(): intDict = {} intDict['class'] = "NETINTERFACES" if not ethtool_present and not netifaces_present: # ethtool is not available on non-linux platforms (as kfreebsd), skip it sys.stderr.write( "Warning: information about network interfaces could not be retrieved on this platform.\n" ) return intDict if ethtool_present: interfaces = list( set(ethtool.get_devices() + ethtool.get_active_devices())) else: interfaces = netifaces.interfaces() for interface in interfaces: try: if ethtool_present: hwaddr = ethtool.get_hwaddr(interface) else: hwaddr = netifaces.ifaddresses(interface)[ netifaces.AF_LINK][0]['addr'] except: hwaddr = "" # slave devices can have their hwaddr changed try: master = os.readlink('/sys/class/net/%s/master' % interface) except: master = None if master: master_interface = os.path.basename(master) hwaddr = get_slave_hwaddr(master_interface, interface) try: if ethtool_present: module = ethtool.get_module(interface) else: driver_file = open( '/sys/class/net/%s/device/uevent' % interface, 'r') module = driver_file.readline().split('=')[1].strip() driver_file.close() except: if interface == 'lo': module = "loopback" else: module = "Unknown" try: if ethtool_present: ipaddr = ethtool.get_ipaddr(interface) else: ipaddr = netifaces.ifaddresses(interface)[ netifaces.AF_INET][0]['addr'] except: ipaddr = "" try: if ethtool_present: netmask = ethtool.get_netmask(interface) else: netmask = netifaces.ifaddresses(interface)[ netifaces.AF_INET][0]['netmask'] except: netmask = "" try: if ethtool_present: broadcast = ethtool.get_broadcast(interface) else: broadcast = netifaces.ifaddresses(interface)[ netifaces.AF_INET][0]['broadcast'] except: broadcast = "" ip6_list = [] if ethtool_present: dev_info = ethtool.get_interfaces_info(interface) for info in dev_info: # one interface may have more IPv6 addresses for ip6 in info.get_ipv6_addresses(): scope = ip6.scope if scope == 'global': scope = 'universe' ip6_list.append({ 'scope': scope, 'addr': ip6.address, 'netmask': ip6.netmask }) else: try: for dev_info in netifaces.ifaddresses(interface)[ netifaces.AF_INET6]: ip6_addr = dev_info['addr'].split('%')[0] scope_info = ipaddress.IPv6Address(ip6_addr) if scope_info.is_global: scope = 'universe' elif scope_info.is_link_local: scope = 'link' elif scope_info.is_loopback: scope = 'host' elif scope_info.is_site_local: scope = 'site' # count number of '1' bits in netmask returned by netifaces ip6_netmask = dev_info['netmask'] netmask_bits = 0 for two_octets in ip6_netmask.split(':'): if not two_octets: break elif two_octets.lower() == 'ffff': netmask_bits += 16 else: # remove '0b' from begin and find last '1' in the string netmask_bits += 1 + bin( int(two_octets.split('/')[0], 16))[2:].rindex('1') ip6_list.append({ 'scope': scope, 'addr': ip6_addr, 'netmask': netmask_bits }) except KeyError: pass # no ipv6 for this interface intDict[interface] = { 'hwaddr': hwaddr, 'ipaddr': ipaddr, 'netmask': netmask, 'broadcast': broadcast, 'module': module, 'ipv6': ip6_list } return intDict
def get_network_interfaces(self): netinfdict = {} old_ipv4_metakeys = ['ipv4_address', 'ipv4_netmask', 'ipv4_broadcast'] ipv4_metakeys = ['address', 'netmask', 'broadcast'] ipv6_metakeys = ['address', 'netmask'] try: interfaces_info = ethtool.get_interfaces_info( ethtool.get_devices()) for info in interfaces_info: mac_address = info.mac_address device = info.device # Omit mac addresses for sit and lo device types. See BZ838123 # mac address are per interface, not per address if self._should_get_mac_address(device): key = '.'.join(['net.interface', device, 'mac_address']) netinfdict[key] = mac_address # all of our supported versions of python-ethtool support # get_ipv6_addresses for addr in info.get_ipv6_addresses(): # ethtool returns a different scope for "public" IPv6 addresses # on different versions of RHEL. EL5 is "global", while EL6 is # "universe". Make them consistent. scope = addr.scope if scope == 'universe': scope = 'global' for mkey in ipv6_metakeys: key = '.'.join([ 'net.interface', info.device, 'ipv6_%s' % (mkey), scope ]) list_key = "%s_list" % key # we could specify a default here... that could hide # api breakage though and unit testing hw detect is... meh attr = getattr(addr, mkey) or 'Unknown' netinfdict[key] = attr if not netinfdict.get(list_key, None): netinfdict[list_key] = str(attr) else: netinfdict[list_key] += ', %s' % str(attr) # However, old version of python-ethtool do not support # get_ipv4_address # # python-ethtool's api changed between rhel6.3 and rhel6.4 # (0.6-1.el6 to 0.6-2.el6) # (without revving the upstream version... bad python-ethtool!) # note that 0.6-5.el5 (from rhel5.9) has the old api # # previously, we got the 'ipv4_address' from the etherinfo object # directly. In the new api, that isn't exposed, so we get the list # of addresses on the interface, and populate the info from there. # # That api change as to address bz #759150. The bug there was that # python-ethtool only showed one ip address per interface. To # accomdate the finer grained info, the api changed... if hasattr(info, 'get_ipv4_addresses'): for addr in info.get_ipv4_addresses(): for mkey in ipv4_metakeys: # append 'ipv4_' to match the older interface and keeps facts # consistent key = '.'.join([ 'net.interface', info.device, 'ipv4_%s' % (mkey) ]) list_key = "%s_list" % key attr = getattr(addr, mkey) or 'Unknown' netinfdict[key] = attr if not netinfdict.get(list_key, None): netinfdict[list_key] = str(attr) else: netinfdict[list_key] += ', %s' % str(attr) # check to see if we are actually an ipv4 interface elif hasattr(info, 'ipv4_address'): for mkey in old_ipv4_metakeys: key = '.'.join(['net.interface', device, mkey]) attr = getattr(info, mkey) or 'Unknown' netinfdict[key] = attr # otherwise we are ipv6 and we handled that already # bonded slave devices can have their hwaddr changed # # "master" here refers to the slave's master device. # If we find a master link, we are a slave, and we need # to check the /proc/net/bonding info to see what the # "permanent" hw address are for this slave try: master = os.readlink('/sys/class/net/%s/master' % info.device) # FIXME except Exception: master = None if master: master_interface = os.path.basename(master) permanent_mac_addr = self._get_slave_hwaddr( master_interface, info.device) key = '.'.join([ 'net.interface', info.device, "permanent_mac_address" ]) netinfdict[key] = permanent_mac_addr except Exception as e: log.exception(e) log.warning("Error reading network interface information: %s", e) return netinfdict