示例#1
0
    def _functions_accepting_devnames(self, devname):
        self.assertIsString(devname)

        scraped = ifconfig.get_device_by_name(devname)

        try:
            broadcast = ethtool.get_broadcast(devname)
        except (OSError, IOError):
            # Some devices might end up with
            # [Errno 99] Cannot assign requested address
            # That's IOError on 2.7, OSError on 3
            assignable = False
        else:
            assignable = True
            self.assertIsString(broadcast)

            # Broadcast is optional in ifconfig output
            if scraped.broadcast:
                self.assertEqualIpv4Str(broadcast, scraped.broadcast)

        self.assertIsStringExceptForLoopback(
            ethtool.get_businfo, devname, '[Errno 95] Operation not '
            'supported')

        self.assertIsInt(ethtool.get_flags(devname))
        # flagsint cannot be obtained from old ifconfig format
        if not ifconfig.oldFormat:
            self.assertEqual(ethtool.get_flags(devname), scraped.flagsint)
        self.assertIsInt(ethtool.get_gso(devname))
        self.assertIsInt(ethtool.get_gro(devname))
        self.assertIsString(ethtool.get_hwaddr(devname))
        self.assertEqualHwAddr(ethtool.get_hwaddr(devname), scraped.hwaddr)

        if assignable:
            self.assertIsString(ethtool.get_ipaddr(devname))
            self.assertEqual(ethtool.get_ipaddr(devname), scraped.inet)

        self.assertIsStringExceptForLoopback(
            ethtool.get_module, devname, '[Errno 95] Operation not '
            'supported')

        if assignable:
            self.assertIsString(ethtool.get_netmask(devname))
            self.assertEqual(ethtool.get_netmask(devname), scraped.netmask)

        # Operation is not supported only on loopback device
        if devname == 'lo':
            self.assertRaisesIOError(ethtool.get_ringparam, (devname, ),
                                     '[Errno 95] Operation not supported')

        self.assertIsInt(ethtool.get_sg(devname))

        try:
            self.assertIsInt(ethtool.get_ufo(devname))
        except (OSError, IOError):
            # This test may fail due to insufficient privileges
            # That's IOError on 2.7, OSError (PermissionError) on 3
            pass

        self.assertIsInt(ethtool.get_tso(devname))
示例#2
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
示例#3
0
def GetInfoString():
    active_interfaces = ethtool.get_active_devices()
    all_interfaces = GetInterfaceList()

    for i in active_interfaces:
        if ethtool.get_flags('%s' % i) & ethtool.IFF_POINTOPOINT:
            active_interfaces.remove(i)

    ret = ''

    for inter in active_interfaces:
        if inter in all_interfaces:
            all_interfaces.remove(inter)
        else:
            continue
        t = 'Static'
        if IsInterfaceDHCP(inter):
            t = 'DHCP'
        ret = ret + '     %s - Active, %s\n' % (inter, t)
        ret = ret + '     IP: %s\n' % ethtool.get_ipaddr(inter)
        ret = ret + '     Netmask: %s\n' % ethtool.get_netmask(inter)
        ret = ret + '     HWAddr: %s\n' % ethtool.get_hwaddr(inter)
        
    for inter in all_interfaces:
        t = 'Static'
        if IsInterfaceDHCP(inter):
            t = 'DHCP'
        ret = ret + '     %s - Inactive, %s\n' % (inter, t)
        if t == 'Static':
            ip, mask, gw, dns = GetInterfaceConf(inter)
            ret = ret + '     IP: %s\n' % ip
            ret = ret + '     Netmask: %s\n' % mask
        ret = ret + '     HWAddr: %s\n' % ethtool.get_hwaddr(inter)
        
    return ret
示例#4
0
    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}
示例#5
0
    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,
        }
示例#6
0
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
示例#7
0
def make_ocd_conf(conf, tpl):
    conf.register_opts(ocd_opts, group='openconfigd')

    config = {
        'wan_device': conf.openconfigd.wan_device,
        'wan_ipv4': conf.openconfigd.wan_ipv4,
        'wan_ipv4_prefix_length': conf.openconfigd.wan_ipv4_prefix_length,
        'remote_ipv4': conf.openconfigd.remote_ipv4,
        'local_device': conf.openconfigd.local_device,
        'local_ipv4': conf.openconfigd.local_ipv4,
        'local_ipv4_prefix_length': conf.openconfigd.local_ipv4_prefix_length,
    }

    if conf.openconfigd.wanif:
        if config['wan_ipv4'] == None:
            config['wan_ipv4'] = ethtool.get_ipaddr(conf.openconfigd.wanif)
            config['wan_ipv4_prefix_length'] = mask2length(
                ethtool.get_netmask(conf.openconfigd.wanif))
            config['wan_device'] = device_id(conf.openconfigd.wanif)
            conf.set_override('wan_ipv4',
                              config['wan_ipv4'],
                              group="openconfigd")
            conf.set_override('wan_ipv4_prefix_length',
                              config['wan_ipv4_prefix_length'],
                              group="openconfigd")
            conf.set_override('wan_device',
                              config['wan_device'],
                              group="openconfigd")

    if conf.openconfigd.lanif:
        if config['local_ipv4'] == None:
            config['local_ipv4'] = ethtool.get_ipaddr(conf.openconfigd.lanif)
            config['local_ipv4_prefix_length'] = mask2length(
                ethtool.get_netmask(conf.openconfigd.lanif))
            config['local_device'] = device_id(conf.openconfigd.lanif)
            conf.set_override('local_ipv4',
                              config['local_ipv4'],
                              group="openconfigd")
            conf.set_override('local_ipv4_prefix_length',
                              config['local_ipv4_prefix_length'],
                              group="openconfigd")
            conf.set_override('local_device',
                              config['local_device'],
                              group="openconfigd")

    return tpl.render(config)
示例#8
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
示例#9
0
    def _functions_accepting_devnames(self, devname):
        self.assertIsString(devname)

        scraped = ifconfig.get_device_by_name(devname)

        self.assertIsString(ethtool.get_broadcast(devname))
        self.assertEqualIpv4Str(ethtool.get_broadcast(devname),
                                scraped.broadcast)

        self.assertIsStringExceptForLoopback(
            ethtool.get_businfo, devname, '[Errno 95] Operation not supported')

        # ethtool.get_coalesce(devname)
        # this gives me:
        #   IOError: [Errno 95] Operation not supported
        # on my test box

        self.assertIsInt(ethtool.get_flags(devname))
        # flagsint cannot be obtained from old ifconfig format
        if not ifconfig.oldFormat:
            self.assertEqual(ethtool.get_flags(devname), scraped.flagsint)
        self.assertIsInt(ethtool.get_gso(devname))

        self.assertIsString(ethtool.get_hwaddr(devname))
        self.assertEqualHwAddr(ethtool.get_hwaddr(devname), scraped.hwaddr)
        self.assertIsString(ethtool.get_ipaddr(devname))
        self.assertEqual(ethtool.get_ipaddr(devname), scraped.inet)

        self.assertIsStringExceptForLoopback(
            ethtool.get_module, devname, '[Errno 95] Operation not supported')

        self.assertIsString(ethtool.get_netmask(devname))
        self.assertEqual(ethtool.get_netmask(devname), scraped.netmask)

        #self.assertRaisesIOError(ethtool.get_ringparam, (devname, ),
        #                         '[Errno 95] Operation not supported')

        # Disabling until BZ#703089 is investigated
        #self.assertIsInt(ethtool.get_sg(devname))
        #self.assertIsInt(ethtool.get_ufo(devname))

        self.assertIsInt(ethtool.get_tso(devname))
示例#10
0
    def _functions_accepting_devnames(self, devname):
        self.assertIsString(devname)

        scraped = ifconfig.get_device_by_name(devname)

        self.assertIsString(ethtool.get_broadcast(devname))
        self.assertEqualIpv4Str(ethtool.get_broadcast(devname), scraped.broadcast)

        self.assertIsStringExceptForLoopback(ethtool.get_businfo, devname, "[Errno 95] Operation not supported")

        # ethtool.get_coalesce(devname)
        # this gives me:
        #   IOError: [Errno 95] Operation not supported
        # on my test box

        self.assertIsInt(ethtool.get_flags(devname))
        # flagsint cannot be obtained from old ifconfig format
        if not ifconfig.oldFormat:
            self.assertEqual(ethtool.get_flags(devname), scraped.flagsint)
        self.assertIsInt(ethtool.get_gso(devname))

        self.assertIsString(ethtool.get_hwaddr(devname))
        self.assertEqualHwAddr(ethtool.get_hwaddr(devname), scraped.hwaddr)
        self.assertIsString(ethtool.get_ipaddr(devname))
        self.assertEqual(ethtool.get_ipaddr(devname), scraped.inet)

        self.assertIsStringExceptForLoopback(ethtool.get_module, devname, "[Errno 95] Operation not supported")

        self.assertIsString(ethtool.get_netmask(devname))
        self.assertEqual(ethtool.get_netmask(devname), scraped.netmask)

        # self.assertRaisesIOError(ethtool.get_ringparam, (devname, ),
        #                         '[Errno 95] Operation not supported')

        # Disabling until BZ#703089 is investigated
        # self.assertIsInt(ethtool.get_sg(devname))
        # self.assertIsInt(ethtool.get_ufo(devname))

        self.assertIsInt(ethtool.get_tso(devname))
示例#11
0
    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
示例#12
0
def show_config(device):
    ipaddr = ethtool.get_ipaddr(device)
    netmask = ethtool.get_netmask(device)
    flags = ethtool.get_flags(device)
    print '%-9.9s' % device,
    if not (flags & ethtool.IFF_LOOPBACK):
        print "HWaddr %s" % ethtool.get_hwaddr(device),
    print '''
          inet addr:%s''' % ipaddr,
    if not (flags & (ethtool.IFF_LOOPBACK | ethtool.IFF_POINTOPOINT)):
        print "Bcast:%s" % ethtool.get_broadcast(device),
    print '''  Mask:%s
          %s
''' % (netmask, flags2str(flags))
示例#13
0
文件: network.py 项目: XaF/rteval
    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
示例#14
0
def show_config(device):
	ipaddr = ethtool.get_ipaddr(device)
	netmask = ethtool.get_netmask(device)
	flags = ethtool.get_flags(device)
	print '%-9.9s' % device,
	if not (flags & ethtool.IFF_LOOPBACK):
		print "HWaddr %s" % ethtool.get_hwaddr(device),
	print '''
          inet addr:%s''' % ipaddr,
	if not (flags & (ethtool.IFF_LOOPBACK | ethtool.IFF_POINTOPOINT)):
		print "Bcast:%s" % ethtool.get_broadcast(device),
	print '''  Mask:%s
	  %s
''' % (netmask, flags2str(flags))
示例#15
0
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
    }
示例#16
0
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}
示例#17
0
文件: utils.py 项目: jdobes/koan
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
示例#18
0
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
示例#19
0
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)}
示例#20
0
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}
示例#21
0
文件: netinfo.py 项目: shaohef/kimchi
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
    }
示例#22
0
def show_config(device):
	ipaddr = ethtool.get_ipaddr(device)
	netmask = ethtool.get_netmask(device)
	flags = ethtool.get_flags(device)
	print '%-9.9s' % device,
	if not (flags & ethtool.IFF_LOOPBACK):
		print "HWaddr %s" % ethtool.get_hwaddr(device),
	print '''
          inet addr:%s''' % ipaddr,
	if not (flags & (ethtool.IFF_LOOPBACK | ethtool.IFF_POINTOPOINT)):
		print "Bcast:%s" % ethtool.get_broadcast(device),
	print '  Mask:%s' % netmask
	for info in ethtool.get_interfaces_info(device):
		for addr in info.get_ipv6_addresses():
			print ("	  inet6 addr: %s/%s Scope: %s"
			       % (addr.address,
				  addr.netmask,
				  addr.scope))
	print '	  %s' % flags2str(flags)
	print
示例#23
0
文件: netinfo.py 项目: mahak/kimchi
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}
示例#24
0
文件: netinfo.py 项目: madhawa/kimchi
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,
    }
示例#25
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
示例#26
0
def read_network_interfaces():
    intDict = {}
    intDict['class'] = "NETINTERFACES"

    if not ethtool_present:
        # ethtool is not available on non-linux platforms (as kfreebsd), skip it
        return intDict

    interfaces = list(set(ethtool.get_devices() +
                          ethtool.get_active_devices()))
    for interface in interfaces:
        try:
            hwaddr = ethtool.get_hwaddr(interface)
        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:
            module = ethtool.get_module(interface)
        except:
            if interface == 'lo':
                module = "loopback"
            else:
                module = "Unknown"
        try:
            ipaddr = ethtool.get_ipaddr(interface)
        except:
            ipaddr = ""

        try:
            netmask = ethtool.get_netmask(interface)
        except:
            netmask = ""

        try:
            broadcast = ethtool.get_broadcast(interface)
        except:
            broadcast = ""

        ip6_list = []
        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
                })
        intDict[interface] = {
            'hwaddr': hwaddr,
            'ipaddr': ipaddr,
            'netmask': netmask,
            'broadcast': broadcast,
            'module': module,
            'ipv6': ip6_list
        }

    return intDict
示例#27
0
文件: rteval.py 项目: sconklin/rteval
    def genxml(self, duration, accum, samples, xslt=None):
        seconds = duration.seconds
        hours = seconds / 3600
        if hours:
            seconds -= hours * 3600
        minutes = seconds / 60
        if minutes:
            seconds -= minutes * 60
        (sys, node, release, ver, machine) = os.uname()

        # Start new XML report
        self.xmlreport = xmlout.XMLOut("rteval", self.version)
        self.xmlreport.NewReport()

        self.xmlreport.openblock(
            "run_info", {"days": duration.days, "hours": hours, "minutes": minutes, "seconds": seconds}
        )
        self.xmlreport.taggedvalue("date", self.start.strftime("%Y-%m-%d"))
        self.xmlreport.taggedvalue("time", self.start.strftime("%H:%M:%S"))
        if self.annotate:
            self.xmlreport.taggedvalue("annotate", self.annotate)
        self.xmlreport.closeblock()
        self.xmlreport.openblock("uname")
        self.xmlreport.taggedvalue("node", node)
        isrt = 1
        if ver.find(" RT ") == -1:
            isrt = 0
        self.xmlreport.taggedvalue("kernel", release, {"is_RT": isrt})
        self.xmlreport.taggedvalue("arch", machine)
        self.xmlreport.taggedvalue("baseos", self.baseos)
        self.xmlreport.closeblock()

        self.xmlreport.openblock("clocksource")
        self.xmlreport.taggedvalue("current", self.current_clocksource)
        self.xmlreport.taggedvalue("available", self.available_clocksource)
        self.xmlreport.closeblock()

        self.xmlreport.openblock("hardware")
        self.xmlreport.AppendXMLnodes(self.cputopology)
        self.xmlreport.taggedvalue("numa_nodes", self.numanodes)
        self.xmlreport.taggedvalue("memory_size", "%.3f" % self.memsize[0], {"unit": self.memsize[1]})
        self.xmlreport.closeblock()

        self.xmlreport.openblock("services")
        for s in self.services:
            self.xmlreport.taggedvalue("service", self.services[s], {"name": s})
        self.xmlreport.closeblock()

        keys = self.kthreads.keys()
        if len(keys):
            keys.sort()
            self.xmlreport.openblock("kthreads")
            for pid in keys:
                self.xmlreport.taggedvalue(
                    "thread",
                    self.kthreads[pid]["name"],
                    {"policy": self.kthreads[pid]["policy"], "priority": self.kthreads[pid]["priority"]},
                )
            self.xmlreport.closeblock()

        modlist = util.get_modules()
        if len(modlist):
            self.xmlreport.openblock("kernelmodules")
            for mod in modlist:
                self.xmlreport.openblock("module")
                self.xmlreport.taggedvalue(
                    "info",
                    mod["modname"],
                    {"size": mod["modsize"], "state": mod["modstate"], "numusers": mod["numusers"]},
                )
                if mod["usedby"] != "-":
                    self.xmlreport.openblock("usedby")
                    for ub in mod["usedby"].split(","):
                        if len(ub):
                            self.xmlreport.taggedvalue("module", ub, None)
                    self.xmlreport.closeblock()
                self.xmlreport.closeblock()
            self.xmlreport.closeblock()

        #
        # Retrieve configured IP addresses
        #
        self.xmlreport.openblock("network_config")

        # Get the interface name for the IPv4 default gw
        route = open("/proc/net/route")
        defgw4 = None
        if route:
            rl = route.readline()
            while rl != "":
                rl = route.readline()
                splt = rl.split("\t")
                if len(splt) > 2 and splt[2] != "00000000":  # Only catch default route
                    defgw4 = splt[0]
                    break
            route.close()

        # Get lists over all devices, remove loopback device
        ifdevs = ethtool.get_active_devices()
        ifdevs.remove("lo")
        ifdevs.sort()

        # Make an interface tag for each device found
        for dev in ifdevs:
            self.xmlreport.openblock("interface", {"device": dev, "hwaddr": ethtool.get_hwaddr(dev)})
            # Protcol configurations
            self.xmlreport.openblock(
                "IPv4",
                {
                    "ipaddr": ethtool.get_ipaddr(dev),
                    "netmask": ethtool.get_netmask(dev),
                    "defaultgw": (defgw4 == dev) and "1" or "0",
                },
            )
            self.xmlreport.closeblock()
            self.xmlreport.closeblock()
        self.xmlreport.closeblock()

        self.xmlreport.openblock("loads", {"load_average": str(accum / samples)})
        for load in self.loads:
            load.genxml(self.xmlreport)
        self.xmlreport.closeblock()
        self.cyclictest.genxml(self.xmlreport)

        # now generate the dmidecode data for this host
        d = dmi.DMIinfo(self.config.GetSection("rteval"))
        d.genxml(self.xmlreport)

        # Close the report - prepare for return the result
        self.xmlreport.close()

        # Write XML (or write XSLT parsed XML if xslt != None)
        if self.xml != None:
            self.xmlreport.Write(self.xml, xslt)
        else:
            # If no file is set, use stdout
            self.xmlreport.Write("-", xslt)  # libxml2 defines a filename as "-" to be stdout
示例#28
0
def read_network_interfaces():
    intDict = {}
    intDict['class'] = "NETINTERFACES"
    
    interfaces = ethtool.get_devices()
    for interface in interfaces:
        try:
            hwaddr = ethtool.get_hwaddr(interface)
        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:
            module = ethtool.get_module(interface)
        except:
            if interface == 'lo':
                module = "loopback"
            else:
                module = "Unknown"
        try:
            ipaddr = ethtool.get_ipaddr(interface)
        except:
            ipaddr = ""

        try:
            netmask = ethtool.get_netmask(interface)
        except:
            netmask = ""

        try:
            broadcast = ethtool.get_broadcast(interface)
        except:
            broadcast = ""
            
        ip6_list = []
        try:
            # one interface may have more IPv6 addresses
            for ip6 in dev.get_ipv6_addresses():
                ip6_list.append({
                    'scope':   ip6.scope,
                    'addr':    ip6.address, 
                    'netmask': ip6.netmask
                })
        except:
            pass
        intDict[interface] = {'hwaddr':hwaddr,
                              'ipaddr':ipaddr,
                              'netmask':netmask,
                              'broadcast':broadcast,
                              'module': module,
                              'ipv6': ip6_list}

    return intDict
示例#29
0
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
示例#30
0
    def genxml(self, duration, accum, samples, xslt=None):
        seconds = duration.seconds
        hours = seconds / 3600
        if hours: seconds -= (hours * 3600)
        minutes = seconds / 60
        if minutes: seconds -= (minutes * 60)
        (sys, node, release, ver, machine) = os.uname()

        # Start new XML report
        self.xmlreport = xmlout.XMLOut('rteval', self.version)
        self.xmlreport.NewReport()

        self.xmlreport.openblock(
            'run_info', {
                'days': duration.days,
                'hours': hours,
                'minutes': minutes,
                'seconds': seconds
            })
        self.xmlreport.taggedvalue('date', self.start.strftime('%Y-%m-%d'))
        self.xmlreport.taggedvalue('time', self.start.strftime('%H:%M:%S'))
        if self.annotate:
            self.xmlreport.taggedvalue('annotate', self.annotate)
        self.xmlreport.closeblock()
        self.xmlreport.openblock('uname')
        self.xmlreport.taggedvalue('node', node)
        isrt = 1
        if ver.find(' RT ') == -1:
            isrt = 0
        self.xmlreport.taggedvalue('kernel', release, {'is_RT': isrt})
        self.xmlreport.taggedvalue('arch', machine)
        self.xmlreport.taggedvalue('baseos', self.baseos)
        self.xmlreport.closeblock()

        self.xmlreport.openblock("clocksource")
        self.xmlreport.taggedvalue('current', self.current_clocksource)
        self.xmlreport.taggedvalue('available', self.available_clocksource)
        self.xmlreport.closeblock()

        self.xmlreport.openblock('hardware')
        self.xmlreport.AppendXMLnodes(self.cputopology)
        self.xmlreport.taggedvalue('numa_nodes', self.numanodes)
        self.xmlreport.taggedvalue('memory_size', "%.3f" % self.memsize[0],
                                   {"unit": self.memsize[1]})
        self.xmlreport.closeblock()

        self.xmlreport.openblock('services', {'init': self.init})
        for s in self.services:
            self.xmlreport.taggedvalue("service", self.services[s],
                                       {"name": s})
        self.xmlreport.closeblock()

        keys = self.kthreads.keys()
        if len(keys):
            keys.sort()
            self.xmlreport.openblock('kthreads')
            for pid in keys:
                self.xmlreport.taggedvalue(
                    'thread', self.kthreads[pid]['name'], {
                        'policy': self.kthreads[pid]['policy'],
                        'priority': self.kthreads[pid]['priority'],
                    })
            self.xmlreport.closeblock()

        modlist = util.get_modules()
        if len(modlist):
            self.xmlreport.openblock('kernelmodules')
            for mod in modlist:
                self.xmlreport.openblock('module')
                self.xmlreport.taggedvalue(
                    'info', mod['modname'], {
                        'size': mod['modsize'],
                        'state': mod['modstate'],
                        'numusers': mod['numusers']
                    })
                if mod['usedby'] != '-':
                    self.xmlreport.openblock('usedby')
                    for ub in mod['usedby'].split(','):
                        if len(ub):
                            self.xmlreport.taggedvalue('module', ub, None)
                    self.xmlreport.closeblock()
                self.xmlreport.closeblock()
            self.xmlreport.closeblock()

        #
        # Retrieve configured IP addresses
        #
        self.xmlreport.openblock('network_config')

        # Get the interface name for the IPv4 default gw
        route = open('/proc/net/route')
        defgw4 = None
        if route:
            rl = route.readline()
            while rl != '':
                rl = route.readline()
                splt = rl.split("\t")
                # Only catch default route
                if len(splt) > 2 and splt[2] != '00000000' and splt[
                        1] == '00000000':
                    defgw4 = splt[0]
                    break
            route.close()

        # 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

                self.xmlreport.openblock('interface', {
                    'device': dev.device,
                    'hwaddr': dev.mac_address
                })

                # Protcol configurations
                if dev.ipv4_address:
                    self.xmlreport.openblock(
                        'IPv4', {
                            'ipaddr': dev.ipv4_address,
                            'netmask': dev.ipv4_netmask,
                            'broadcast': dev.ipv4_broadcast,
                            'defaultgw': (defgw4 == dev.device) and '1' or '0'
                        })
                    self.xmlreport.closeblock()

                for ip6 in dev.get_ipv6_addresses():
                    self.xmlreport.openblock(
                        'IPv6', {
                            'ipaddr': ip6.address,
                            'netmask': ip6.netmask,
                            'scope': ip6.scope
                        })
                    self.xmlreport.closeblock()
                self.xmlreport.closeblock()
        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:
                self.xmlreport.openblock('interface', {
                    'device': dev,
                    'hwaddr': ethtool.get_hwaddr(dev)
                })
                self.xmlreport.openblock(
                    'IPv4', {
                        'ipaddr': ethtool.get_ipaddr(dev),
                        'netmask': ethtool.get_netmask(dev),
                        'defaultgw': (defgw4 == dev) and '1' or '0'
                    })
                self.xmlreport.closeblock()
                self.xmlreport.closeblock()
        self.xmlreport.closeblock()

        self.xmlreport.openblock('loads',
                                 {'load_average': str(accum / samples)})
        for load in self.loads:
            load.genxml(self.xmlreport)
        self.xmlreport.closeblock()
        self.cyclictest.genxml(self.xmlreport)

        # now generate the dmidecode data for this host
        d = dmi.DMIinfo(self.config.GetSection('rteval'))
        d.genxml(self.xmlreport)

        # Close the report - prepare for return the result
        self.xmlreport.close()

        # Write XML (or write XSLT parsed XML if xslt != None)
        if self.xml != None:
            self.xmlreport.Write(self.xml, xslt)
        else:
            # If no file is set, use stdout
            self.xmlreport.Write(
                "-", xslt)  # libxml2 defines a filename as "-" to be stdout
示例#31
0
    def genxml(self, duration, accum, samples, xslt = None):
        seconds = duration.seconds
        hours = seconds / 3600
        if hours: seconds -= (hours * 3600)
        minutes = seconds / 60
        if minutes: seconds -= (minutes * 60)
        (sys, node, release, ver, machine) = os.uname()

        # Start new XML report
        self.xmlreport = xmlout.XMLOut('rteval', self.version)
        self.xmlreport.NewReport()

        self.xmlreport.openblock('run_info', {'days': duration.days,
                                 'hours': hours,
                                 'minutes': minutes,
                                 'seconds': seconds})
        self.xmlreport.taggedvalue('date', self.start.strftime('%Y-%m-%d'))
        self.xmlreport.taggedvalue('time', self.start.strftime('%H:%M:%S'))
        if self.annotate:
            self.xmlreport.taggedvalue('annotate', self.annotate)
        self.xmlreport.closeblock()
        self.xmlreport.openblock('uname')
        self.xmlreport.taggedvalue('node', node)
        isrt = 1
        if ver.find(' RT ') == -1:
            isrt = 0
        self.xmlreport.taggedvalue('kernel', release, {'is_RT':isrt})
        self.xmlreport.taggedvalue('arch', machine)
        self.xmlreport.taggedvalue('baseos', self.baseos)
        self.xmlreport.closeblock()

        self.xmlreport.openblock("clocksource")
        self.xmlreport.taggedvalue('current', self.current_clocksource)
        self.xmlreport.taggedvalue('available', self.available_clocksource)
        self.xmlreport.closeblock()

        self.xmlreport.openblock('hardware')
        self.xmlreport.AppendXMLnodes(self.cputopology)
        self.xmlreport.taggedvalue('numa_nodes', self.numanodes)
        self.xmlreport.taggedvalue('memory_size', "%.3f" % self.memsize[0], {"unit": self.memsize[1]})
        self.xmlreport.closeblock()

        self.xmlreport.openblock('services', {'init': self.init})
        for s in self.services:
            self.xmlreport.taggedvalue("service", self.services[s], {"name": s})
        self.xmlreport.closeblock()

        keys = self.kthreads.keys()
        if len(keys):
            keys.sort()
            self.xmlreport.openblock('kthreads')
            for pid in keys:
                self.xmlreport.taggedvalue('thread', self.kthreads[pid]['name'],
                                           { 'policy' : self.kthreads[pid]['policy'],
                                             'priority' : self.kthreads[pid]['priority'],
                                             })
            self.xmlreport.closeblock()

        modlist = util.get_modules()
        if len(modlist):
            self.xmlreport.openblock('kernelmodules')
            for mod in modlist:
                self.xmlreport.openblock('module')
                self.xmlreport.taggedvalue('info', mod['modname'],
                                           {'size': mod['modsize'],
                                            'state': mod['modstate'],
                                            'numusers': mod['numusers']})
                if mod['usedby'] != '-':
                    self.xmlreport.openblock('usedby')
                    for ub in mod['usedby'].split(','):
                        if len(ub):
                            self.xmlreport.taggedvalue('module', ub, None)
                    self.xmlreport.closeblock()
                self.xmlreport.closeblock()
            self.xmlreport.closeblock()

        #
        # Retrieve configured IP addresses
        #
        self.xmlreport.openblock('network_config')

        # Get the interface name for the IPv4 default gw
        route = open('/proc/net/route')
        defgw4 = None
        if route:
            rl = route.readline()
            while rl != '' :
                rl = route.readline()
                splt = rl.split("\t")
                # Only catch default route
                if len(splt) > 2 and splt[2] != '00000000' and splt[1] == '00000000':
                    defgw4 = splt[0]
                    break
            route.close()

        # 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

                self.xmlreport.openblock('interface',
                                         {'device': dev.device,
                                          'hwaddr': dev.mac_address}
                                         )

                # Protcol configurations
                if dev.ipv4_address:
                    self.xmlreport.openblock('IPv4',
                                             {'ipaddr': dev.ipv4_address,
                                              'netmask': dev.ipv4_netmask,
                                              'broadcast': dev.ipv4_broadcast,
                                              'defaultgw': (defgw4 == dev.device) and '1' or '0'}
                                             )
                    self.xmlreport.closeblock()

                for ip6 in dev.get_ipv6_addresses():
                    self.xmlreport.openblock('IPv6',
                                             {'ipaddr': ip6.address,
                                              'netmask': ip6.netmask,
                                              'scope': ip6.scope}
                                             )
                    self.xmlreport.closeblock()
                self.xmlreport.closeblock()
        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:
                self.xmlreport.openblock('interface',
                                         {'device': dev,
                                          'hwaddr': ethtool.get_hwaddr(dev)}
                                         )
                self.xmlreport.openblock('IPv4',
                                         {'ipaddr': ethtool.get_ipaddr(dev),
                                          'netmask': ethtool.get_netmask(dev),
                                          'defaultgw': (defgw4 == dev) and '1' or '0'}
                                         )
                self.xmlreport.closeblock()
                self.xmlreport.closeblock()
        self.xmlreport.closeblock()

        self.xmlreport.openblock('loads', {'load_average':str(accum / samples)})
        for load in self.loads:
            load.genxml(self.xmlreport)
        self.xmlreport.closeblock()
        self.cyclictest.genxml(self.xmlreport)

        # now generate the dmidecode data for this host
        d = dmi.DMIinfo(self.config.GetSection('rteval'))
        d.genxml(self.xmlreport)

        # Close the report - prepare for return the result
        self.xmlreport.close()

        # Write XML (or write XSLT parsed XML if xslt != None)
        if self.xml != None:
            self.xmlreport.Write(self.xml, xslt)
        else:
            # If no file is set, use stdout
            self.xmlreport.Write("-", xslt) # libxml2 defines a filename as "-" to be stdout
示例#32
0
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
示例#33
0
def read_network_interfaces():
    intDict = {}
    intDict['class'] = "NETINTERFACES"

    if not ethtool_present:
        # ethtool is not available on non-linux platforms (as kfreebsd), skip it
        return intDict

    interfaces = list(set(ethtool.get_devices() + ethtool.get_active_devices()))
    for interface in interfaces:
        try:
            hwaddr = ethtool.get_hwaddr(interface)
        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:
            module = ethtool.get_module(interface)
        except:
            if interface == 'lo':
                module = "loopback"
            else:
                module = "Unknown"
        try:
            ipaddr = ethtool.get_ipaddr(interface)
        except:
            ipaddr = ""

        try:
            netmask = ethtool.get_netmask(interface)
        except:
            netmask = ""

        try:
            broadcast = ethtool.get_broadcast(interface)
        except:
            broadcast = ""

        ip6_list = []
        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
                })
        intDict[interface] = {'hwaddr':hwaddr,
                              'ipaddr':ipaddr,
                              'netmask':netmask,
                              'broadcast':broadcast,
                              'module': module,
                              'ipv6': ip6_list}

    return intDict