Esempio n. 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))
Esempio n. 2
0
def route_announce (networks):
	hash = hash_route (networks, ethtool.get_ipaddr (MCAST_LAPIS_IFACE))
	jstr = json.dumps ({
		"len": len (networks),
		"networks": networks,
		"hash": hash,
		"announce_time": MCAST_ANNOUNCE_TIME,
		"localip": ethtool.get_ipaddr (MCAST_LAPIS_IFACE)
	})
	bytes_sent = sock.sendto (jstr, (MCAST_ALL_ROUTER, MCAST_LAPIS_PORT))
	return (len (jstr) == bytes_sent)
Esempio n. 3
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
Esempio n. 4
0
def _getIpAddresses():
    devinfo = {}
    for dev in ethtool.get_active_devices():
        try:
            devinfo[dev] = ethtool.get_ipaddr(dev)
        except IOError, e:
            print e
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
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,
        }
Esempio n. 8
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}
def _getIpAddresses():
    devinfo = {}
    for dev in ethtool.get_active_devices():
        try:
            devinfo[dev] = ethtool.get_ipaddr(dev)
        except IOError, e:
            print e
Esempio n. 10
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)
Esempio n. 11
0
 def _get_active_interface(self, valid_interfaces):
     for iface in valid_interfaces:
         try:
             if (socket.getfqdn(
                     ethtool.get_ipaddr(iface)) == socket.gethostname()):
                 return iface
         except IOError:
             pass
     return valid_interfaces[0]
Esempio n. 12
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
Esempio n. 13
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))
Esempio n. 14
0
 def _get_active_interface(self, valid_interfaces):
     for iface in valid_interfaces:
         try:
             if (
                 socket.getfqdn(ethtool.get_ipaddr(iface)) ==
                 socket.gethostname()
             ):
                 return iface
         except IOError:
             pass
     return valid_interfaces[0]
Esempio n. 15
0
def SaveVmLoginInfo():
    nowtime = datetime.now()
    vmlogintime = nowtime.strftime("%Y-%m-%d %H:%M")
    try:
        act_device = ethtool.get_active_devices()
        if "lo" in act_device:
            act_device.remove("lo")
        for i in act_device:
            clientip = ethtool.get_ipaddr(i)
    except OSError , e:
        Logger.error("Get addr ip failed: %s" % str(e))
Esempio n. 16
0
def LoginInforRequests():
    info = {}
    info["time"] = datetime.now()

    try:
        act_device = ethtool.get_active_devices()
        if "lo" in act_device:
            act_device.remove("lo")
        for i in act_device:
            info["ip"] = ethtool.get_ipaddr(i)
    except OSError , e:
        Logger.error("Get addr ip failed: %s" % str(e))
Esempio n. 17
0
 def get_addrinfo(self,param):
     addr={}
     try:
         act_device = ethtool.get_active_devices()
         if "lo" in act_device:
             act_device.remove("lo")
         for i in act_device:
             mac = ethtool.get_hwaddr(i)
             addr[mac] = ethtool.get_ipaddr(i)
     except OSError , e:
         Logger.error("Get addr information failed: %s" % str(e))
         return
Esempio n. 18
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))
Esempio n. 19
0
def getNonLoopbackAddresses():
    devices = ethtool.get_active_devices()
    iplist = []

    for device in devices:
        try:
            flags = ethtool.get_flags(device)
            if flags and not (flags & ethtool.IFF_LOOPBACK):
                iplist.append(ethtool.get_ipaddr(device))
        except IOError as e:
            logging.error("unable to get ipaddr/flags for %s: %s"
                          % (device, e))
    return set(iplist)
Esempio n. 20
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
Esempio n. 21
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))
Esempio n. 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
	  %s
''' % (netmask, flags2str(flags))
Esempio n. 23
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
    }
Esempio n. 24
0
 def getAllNetworkInterfaces(self):
     interfaces = list()
     try:
         for dev in ethtool.get_active_devices():
             flags = ethtool.get_flags(dev)
             if not(flags & ethtool.IFF_LOOPBACK):
                 devinfo = ethtool.get_interfaces_info(dev)[0]
                 interfaces.append({ 'name' : dev,
                     'inet' : [ ethtool.get_ipaddr(dev) ],
                     'inet6' : map(lambda ip: ip.address, devinfo.get_ipv6_addresses()),
                     'hw' : ethtool.get_hwaddr(dev) })
     except:
         logging.exception("Error retrieving network interfaces.")
     return interfaces
Esempio n. 25
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
Esempio n. 26
0
File: utils.py Progetto: 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
Esempio n. 27
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}
Esempio n. 28
0
def create_sock ():
	logger.info ("Creation du socket")
	sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
	sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	try:
		sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
	except AttributeError:
		pass
	sock.bind (('', MCAST_LAPIS_PORT))
	sock.setsockopt (socket.SOL_IP, socket.IP_MULTICAST_TTL, 2)
	sock.setsockopt (socket.SOL_IP, socket.IP_MULTICAST_LOOP, 0)
	intf = ethtool.get_ipaddr (MCAST_LAPIS_IFACE)
	sock.setsockopt (socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton (intf))
	sock.setsockopt (socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton (MCAST_ALL_ROUTER) + socket.inet_aton (intf))
	sock.settimeout (1)
	return (sock)
Esempio n. 29
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
def _getNetworkInterfaces(interfaces=()):
    if interfaces:
        devices = interfaces
    else:
        devices = ethtool.get_active_devices()

    info = {}
    for dev in devices:
        try:
            info[dev] = {'ipaddr': ethtool.get_ipaddr(dev),
                         'flags': ethtool.get_flags(dev)}
        except IOError as e:
            logging.error("unable to get ipaddr/flags for %s: %s" % (dev, e))
            info[dev] = {'ipaddr': None,
                         'flags': None}

    return info
Esempio n. 31
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)}
Esempio n. 32
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}
Esempio n. 33
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
    }
Esempio n. 34
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
Esempio n. 35
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

    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}
Esempio n. 36
0
def _getLocalPeer():
    global _peer

    if _peer:
        return _peer

    fqdn = socket.getfqdn()
    ip = socket.gethostbyname(fqdn)
    if not ip.startswith('127.'):
        _peer = ip
        return ip

    for dev in ethtool.get_active_devices():
        try:
            ip = ethtool.get_ipaddr(dev)
            if not ip.startswith('127.'):
                _peer = ip
                return ip
        except IOError as e:
            logger.warn('failed to get ipaddr for device %s: %s' % (dev, e))

    return fqdn
Esempio n. 37
0
def get_local_ip():
    ifnames = get_nics()
    for ifname in ifnames:
        config_file='/etc/sysconfig/network-scripts/ifcfg-%s' % ifname
        if os.path.exists(config_file):
            fp = open(config_file,'r')
            is_slave = False
            for line in fp.readlines():
                if line[0] == '#':
                   continue
                if 'SLAVE' in line and 'yes' in line:
                   is_slave = True
                   break
                del line
            if not is_slave:
                try:
                    ip = ethtool.get_ipaddr(ifname)
                    if ip:
                        return ip
                except Exception as e:
                    logger.error(traceback.format_exc())

    return ""
Esempio n. 38
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

    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,
    }
Esempio n. 39
0
def _getLocalPeer():
    global _peer

    if _peer:
        return _peer

    fqdn = socket.getfqdn()
    ip = socket.gethostbyname(fqdn)
    if not ip.startswith('127.'):
        _peer = ip
        return ip

    for dev in ethtool.get_active_devices():
        try:
            ip = ethtool.get_ipaddr(dev)
            if not ip.startswith('127.'):
                _peer = ip
                return ip
        except IOError:
            # TODO: log it
            pass

    return fqdn
Esempio n. 40
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
Esempio n. 41
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
Esempio n. 42
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")
        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
Esempio n. 43
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
Esempio n. 44
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
Esempio n. 45
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
Esempio n. 46
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
Esempio n. 47
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
Esempio n. 48
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