Example #1
0
def _getIpAddresses():
    devinfo = {}
    for dev in ethtool.get_active_devices():
        try:
            devinfo[dev] = ethtool.get_ipaddr(dev)
        except IOError, e:
            print e
Example #2
0
def CheckInternet():
    # turn on the internet and check it's connected
    print "CheckInternet()"
    subprocess.call(["sudo", "dhclient", "eth1"])
    if not "eth1" in ethtool.get_active_devices():
        print "error: eth1 connection is not working"
        sys.exit(1)
Example #3
0
    def checkLocalHostname(self):
        # This is missing and not used on rhel5
        import ethtool

        self.status = "OK"
        self.rc = True
        self.message = "Local hostname is correct."

        try:
            localip = map(ethtool.get_ipaddr, ethtool.get_active_devices())
            localip = filter(lambda x: x != "127.0.0.1", localip)
        except:
            logging.error("ethtool error", exc_info=True)
            localip = ()

        try:
            fqdnip = socket.gethostbyname(socket.gethostname())
        except:
            logging.error("gethostbyname error", exc_info=True)
            fqdnip = None

        if fqdnip is None or fqdnip not in localip:
            if len(localip) < 1:
                self.message = "Unable to get local ip addresses."
            elif fqdnip is None:
                self.message = "Unable to resolve local hostname."
            else:
                self.message = "Local hostname is configured badly."
            self.status = "WARN"
            logging.error(self.message)

        self._xmlOutput('CheckLocalHostname',
                        self.status, None, None, self.message)
        return self.rc
Example #4
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
def _getIpAddresses():
    devinfo = {}
    for dev in ethtool.get_active_devices():
        try:
            devinfo[dev] = ethtool.get_ipaddr(dev)
        except IOError, e:
            print e
 def enable_VF(self, nicName, vfNums):
     cmd = "echo %s > /sys/class/net/%s/device/sriov_numvfs" % (vfNums,
                                                                nicName)
     result = os.popen(cmd).read()
     time.sleep(5)
     self.logger.info(
         _('active nics: {nics}').format(nics=ethtool.get_active_devices()))
    def _customization(self):
        active_ethName = ethtool.get_active_devices()
        self.environment[
            ohostedcons.NetworkEnv.CEPH_NIC_IF] = self.dialog.queryString(
                name='ovehosted_ceph_nic_if',
                note=
                _('Please indicate a nic to active CEPH Public network: (@VALUES@): '
                  ),
                prompt=True,
                caseSensitive=True,
                validValues=active_ethName,
            )
        self.logger.info(
            _('indicate nis is {eth}').format(
                eth=self.environment[ohostedcons.NetworkEnv.CEPH_NIC_IF]))

        self.environment[
            ohostedcons.NetworkEnv.
            CEPH_PUBLIC_IPADDR] = self.dialog.queryString(
                name='ovehosted_ceph_public_ipaddr',
                note=_('Please input your CEPH Public network IPADDR: '),
                prompt=True,
                caseSensitive=True,
            )
        self.logger.info(
            _('ipaddr is {eth}').format(eth=self.environment[
                ohostedcons.NetworkEnv.CEPH_PUBLIC_IPADDR]))

        self.environment[
            ohostedcons.NetworkEnv.
            CEPH_PUBLIC_NETMASK] = self.dialog.queryString(
                name='ovehosted_ceph_public_netmask',
                note=
                _('Please input your CEPH Public network METMASK [@DEFAULT@]: '
                  ),
                prompt=True,
                caseSensitive=True,
                default=ohostedcons.NetworkEnv.CEPH_PUBLIC_NETMASK,
            )
        self.logger.info(
            _('netmask is {eth}').format(eth=self.environment[
                ohostedcons.NetworkEnv.CEPH_PUBLIC_NETMASK]))

        self.environment[
            ohostedcons.NetworkEnv.
            CEPH_PUBLIC_GATEWAY] = self.dialog.queryString(
                name='ovehosted_ceph_public_gateway',
                note=_('Please input your CEPH Public network GATEWAY: '),
                prompt=True,
                caseSensitive=True,
            )
        self.logger.info(
            _('gateway is {eth}').format(eth=self.environment[
                ohostedcons.NetworkEnv.CEPH_PUBLIC_GATEWAY]))

        eth = self.environment[ohostedcons.NetworkEnv.CEPH_NIC_IF]
        ipaddr = self.environment[ohostedcons.NetworkEnv.CEPH_PUBLIC_IPADDR]
        netmask = self.environment[ohostedcons.NetworkEnv.CEPH_PUBLIC_NETMASK]
        gateway = self.environment[ohostedcons.NetworkEnv.CEPH_PUBLIC_GATEWAY]
        create_mgmt_config_file(eth, ipaddr, netmask, gateway)
    def _customization(self):
        active_ethName = ethtool.get_active_devices()
        self.environment[
            ohostedcons.NetworkEnv.VF_IF] = self.dialog.queryString(
                name='ovehosted_vf_if',
                note=_('Please indicate a nic to ebable VF: (@VALUES@): '),
                prompt=True,
                caseSensitive=True,
                validValues=active_ethName,
            )
        self.logger.info(
            _('indicate nis is {eth}').format(
                eth=self.environment[ohostedcons.NetworkEnv.VF_IF]))

        self.check_indicate_nic_status(
            self.environment[ohostedcons.NetworkEnv.VF_IF])

        self.environment[ohostedcons.NetworkEnv.VF_NM] = self.dialog.queryString(
            name='ovehosted_vf_nm',
            note=
            _('Please indicate number of VFs no more than 64: (@VALUES@) [@DEFAULT@]: '
              ),
            prompt=True,
            default='5',
        )

        self.enable_VF(self.environment[ohostedcons.NetworkEnv.VF_IF],
                       self.environment[ohostedcons.NetworkEnv.VF_NM])
Example #9
0
    def checkLocalHostname(self):
        # This is missing and not used on rhel5
        import ethtool

        self.status = "OK"
        self.rc = True
        self.message = "Local hostname is correct."

        try:
            localip = map(ethtool.get_ipaddr, ethtool.get_active_devices())
            localip = filter(lambda x: x != "127.0.0.1", localip)
        except:
            logging.error("ethtool error", exc_info=True)
            localip = ()

        try:
            fqdnip = socket.gethostbyname(socket.gethostname())
        except:
            logging.error("gethostbyname error", exc_info=True)
            fqdnip = None

        if fqdnip is None or fqdnip not in localip:
            if len(localip) < 1:
                self.message = "Unable to get local ip addresses."
            elif fqdnip is None:
                self.message = "Unable to resolve local hostname."
            else:
                self.message = "Local hostname is configured badly."
            self.status = "WARN"
            logging.error(self.message)

        self._xmlOutput('CheckLocalHostname', self.status, None, None,
                        self.message)
        return self.rc
Example #10
0
 def testGetIfaceByIP(self):
     for dev in ethtool.get_interfaces_info(ethtool.get_active_devices()):
         ipaddrs = map(
             lambda etherinfo_ipv6addr: etherinfo_ipv6addr.address,
             dev.get_ipv6_addresses())
         ipaddrs.append(dev.ipv4_address)
         for ip in ipaddrs:
             self.assertEqual(dev.device, netinfo.getIfaceByIP(ip))
Example #11
0
 def testGetIfaceByIP(self):
     for dev in ethtool.get_interfaces_info(ethtool.get_active_devices()):
         ipaddrs = map(
             lambda etherinfo_ipv6addr: etherinfo_ipv6addr.address,
             dev.get_ipv6_addresses())
         ipaddrs.append(dev.ipv4_address)
         for ip in ipaddrs:
             self.assertEqual(dev.device, netinfo.getIfaceByIP(ip))
Example #12
0
	def show(self):
		new_irqs = []
		for sirq in self.irqs.keys():
			try:
				new_irqs.append(int(sirq))
			except:
				continue

		nics = ethtool.get_active_devices()

		row = self.list_store.get_iter_first()
		while row:
			irq = self.list_store.get_value(row, self.COL_NUM)
			# IRQ was unregistered? I.e. driver unloaded?
			if not self.irqs.has_key(irq):
				if self.list_store.remove(row):
					# removed and row now its the next one
					continue
				# Was the last one
				break
			elif tuna.irq_filtered(irq, self.irqs,
					       self.cpus_filtered,
					       self.is_root):
				new_irqs.remove(irq)
				if self.list_store.remove(row):
					# removed and row now its the next one
					continue
				# Was the last one
				break
			else:
				try:
					new_irqs.remove(irq)
					irq_info = self.irqs[irq]
					self.set_irq_columns(row, irq, irq_info, nics)
				except:
					if self.list_store.remove(row):
						# removed and row now its the next one
						continue
					# Was the last one
					break

			row = self.list_store.iter_next(row)

		new_irqs.sort()
		for irq in new_irqs:
			if tuna.irq_filtered(irq, self.irqs, self.cpus_filtered,
					     self.is_root):
				continue
			row = self.list_store.append()
			irq_info = self.irqs[irq]
			try:
				self.set_irq_columns(row, irq, irq_info, nics)
			except:
				self.list_store.remove(row)

		self.treeview.show_all()
Example #13
0
    def show(self):
        new_irqs = []
        for sirq in self.irqs.keys():
            try:
                new_irqs.append(int(sirq))
            except:
                continue

        nics = ethtool.get_active_devices()

        row = self.list_store.get_iter_first()
        while row:
            irq = self.list_store.get_value(row, self.COL_NUM)
            # IRQ was unregistered? I.e. driver unloaded?
            if not self.irqs.has_key(irq):
                if self.list_store.remove(row):
                    # removed and row now its the next one
                    continue
                # Was the last one
                break
            elif tuna.irq_filtered(irq, self.irqs, self.cpus_filtered,
                                   self.is_root):
                new_irqs.remove(irq)
                if self.list_store.remove(row):
                    # removed and row now its the next one
                    continue
                # Was the last one
                break
            else:
                try:
                    new_irqs.remove(irq)
                    irq_info = self.irqs[irq]
                    self.set_irq_columns(row, irq, irq_info, nics)
                except:
                    if self.list_store.remove(row):
                        # removed and row now its the next one
                        continue
                    # Was the last one
                    break

            row = self.list_store.iter_next(row)

        new_irqs.sort()
        for irq in new_irqs:
            if tuna.irq_filtered(irq, self.irqs, self.cpus_filtered,
                                 self.is_root):
                continue
            row = self.list_store.append()
            irq_info = self.irqs[irq]
            try:
                self.set_irq_columns(row, irq, irq_info, nics)
            except:
                self.list_store.remove(row)

        self.treeview.show_all()
Example #14
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))
Example #15
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
Example #16
0
def get_irq_users(irqs, irq, nics = None):
	if not nics:
		nics = ethtool.get_active_devices()
	users = irqs[irq]["users"]
	for u in users:
		if u in nics:
			try:
				users[users.index(u)] = "%s(%s)" % (u, ethtool.get_module(u))
			except IOError:
				# Old kernel, doesn't implement ETHTOOL_GDRVINFO
				pass
	return users
Example #17
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))
Example #18
0
def getIfaceByIP(ip):
    for info in ethtool.get_interfaces_info(ethtool.get_active_devices()):

        for ipv4addr in info.get_ipv4_addresses():
            if ip == ipv4addr.address or ip == IPv4toMapped(ipv4addr.address):
                return info.device

        for ipv6addr in info.get_ipv6_addresses():
            if ip == ipv6addr.address:
                return info.device

    return ''
Example #19
0
 def testGetDeviceByIP(self):
     for dev in ethtool.get_interfaces_info(ethtool.get_active_devices()):
         # Link-local IPv6 addresses are generated from the MAC address,
         # which is shared between a nic and its bridge. Since We don't
         # support having the same IP address on two different NICs, and
         # link-local IPv6 addresses aren't interesting for 'getDeviceByIP'
         # then ignore them in the test
         ipaddrs = [ipv6.address for ipv6 in dev.get_ipv6_addresses()
                    if ipv6.scope != 'link']
         if dev.ipv4_address is not None:
             ipaddrs.append(dev.ipv4_address)
         for ip in ipaddrs:
             self.assertEqual(dev.device, netinfo.getDeviceByIP(ip))
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)
Example #21
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
Example #22
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
Example #23
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
Example #24
0
def run_cmd(cmd, interface, args):
        global tab, all_devices

        active_devices = ethtool.get_active_devices()
        if not interface:
                tab = "  "
                for interface in all_devices:
                        inactive = " (not active)"
                        if interface in active_devices:
                                inactive = ""
                        print "%s%s:" % (interface, inactive)
                        cmd(interface, args)
        else:
                cmd(interface, args)
Example #25
0
def run_cmd(cmd, interface, args):
    global tab, all_devices

    active_devices = ethtool.get_active_devices()
    if not interface:
        tab = "  "
        for interface in all_devices:
            inactive = " (not active)"
            if interface in active_devices:
                inactive = ""
            print "%s%s:" % (interface, inactive)
            cmd(interface, args)
    else:
        cmd(interface, args)
Example #26
0
def getDeviceByIP(ip):
    """
    Get network device by IP address
    :param ip: String representing IPv4 or IPv6, but not link-local IPv6
    """
    for info in ethtool.get_interfaces_info(ethtool.get_active_devices()):
        for ipv4addr in info.get_ipv4_addresses():
            if ip in (ipv4addr.address, IPv4toMapped(ipv4addr.address)):
                return info.device

        for ipv6addr in info.get_ipv6_addresses():
            if ip == ipv6addr.address:
                return info.device

    return ''
Example #27
0
def getDeviceByIP(ip):
    """
    Get network device by IP address
    :param ip: String representing IPv4 or IPv6, but not link-local IPv6
    """
    for info in ethtool.get_interfaces_info(ethtool.get_active_devices()):
        for ipv4addr in info.get_ipv4_addresses():
            if ip in (ipv4addr.address, IPv4toMapped(ipv4addr.address)):
                return info.device

        for ipv6addr in info.get_ipv6_addresses():
            if ip == ipv6addr.address:
                return info.device

    return ''
Example #28
0
 def testGetDeviceByIP(self):
     for dev in ethtool.get_interfaces_info(ethtool.get_active_devices()):
         # Link-local IPv6 addresses are generated from the MAC address,
         # which is shared between a nic and its bridge. Since We don't
         # support having the same IP address on two different NICs, and
         # link-local IPv6 addresses aren't interesting for 'getDeviceByIP'
         # then ignore them in the test
         ipaddrs = [
             ipv6.address for ipv6 in dev.get_ipv6_addresses()
             if ipv6.scope != 'link'
         ]
         if dev.ipv4_address is not None:
             ipaddrs.append(dev.ipv4_address)
         for ip in ipaddrs:
             self.assertEqual(dev.device, netinfo.getDeviceByIP(ip))
Example #29
0
    def _stat_gateway(self):
        res = []
        speeds = ''
        ifaces = ethtool.get_active_devices()

        for i in ifaces:
            eth = os.popen("ethtool " + i).readlines()
            for j in eth:
                if 'Speed' in j:
                    speeds = j
                    speed = filter(str.isdigit, j)
                    if len(speed) > 0:
                        res.append(dict(name=i, speed=int(speed)))

        return res
Example #30
0
def find_suitable_device():
    active_devices = ethtool.get_active_devices()
    for device in active_devices:
        device_flags = ethtool.get_flags(device)
        str_flags = pifc.flags2str(device_flags)
        try:
            wireless_protocol = ethtool.get_wireless_protocol(device)
        except Exception:
            wireless_protocol = None

        if 'UP' in str_flags and 'RUNNING' in str_flags \
                and 'BROADCAST' in str_flags and not wireless_protocol:
            return device

    return None
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
Example #32
0
File: rtpirq.py Project: acmel/ait
def show(irqs, ps):
	irq_list = []
	for sirq in irqs.keys():
		try:
			irq_list.append(int(sirq))
		except:
			continue

	irq_list.sort()

	nics = ethtool.get_active_devices()

	for irq in irq_list:
		info = irqs[irq]
		pids = ps.find_by_name("IRQ-%d" % irq)
		if pids:
			pid = pids[0]
			thread_affinity_list = schedutils.get_affinity(pid)
			if len(thread_affinity_list) <= 4:
				thread_affinity = ",".join("%s" % a for a in thread_affinity_list)
			else:
				thread_affinity = ",".join("0x%x" % a for a in procfs.hexbitmask(schedutils.get_affinity(pid), irqs.nr_cpus))
			rtprio = int(ps[pid]["stat"]["rt_priority"])
		else:
			pid = -1
			rtprio = -1
			thread_affinity = ""

		try:
			irq_affinity_list = info["affinity"]
			if len(irq_affinity_list) <= 4:
				irq_affinity = ",".join("%s" % a for a in irq_affinity_list)
			else:
				irq_affinity = ",".join("0x%x" % a for a in procfs.hexbitmask(irq_affinity_list, irqs.nr_cpus))
		except:
			irq_affinity = ""
		events = reduce(lambda a, b: a + b, info["cpu"])
		users = info["users"]
		for u in users:
			if u in nics:
				users[users.index(u)] = "%s(%s)" % (u, ethtool.get_module(u))
		print "%5d: %5d %5d %11d %8s %8s %s" % (irq, pid, rtprio,
							events, thread_affinity,
						        irq_affinity,
						        ",".join(users))
Example #33
0
def getIfaceByIP(ip):
    for info in ethtool.get_interfaces_info(ethtool.get_active_devices()):

        if hasattr(info, 'get_ipv4_addresses'):
            for ipv4addr in info.get_ipv4_addresses():
                if ip == ipv4addr.address or \
                   ip == IPv4toMapped(ipv4addr.address):
                    return info.device
        else:
            if ip == info.ipv4_address or \
               ip == IPv4toMapped(info.ipv4_address):
                return info.device

        for ipv6addr in info.get_ipv6_addresses():
            if ip == ipv6addr.address:
                return info.device

    return ''
Example #34
0
def main():
	global all_devices

        usage="usage: %prog [interface [interface [interface] ...]]"
        parser = OptionParser(usage=usage)
        (opts, args) = parser.parse_args()

        if args is None or len(args) == 0:
                sel_devs = ethtool.get_active_devices()
        else:
                sel_devs = args

	for device in sel_devs:
                try:
                        show_config(device)
                except Exception, ex:
                        print "** ERROR ** [Device %s]: %s" % (device, str(ex))
                        sys.exit(2)
Example #35
0
File: rtps.py Project: cz172638/ait
def show(ps, cpuinfo, irqs):
    ps_list = []
    for pid in ps.keys():
        if schedutils.get_scheduler(pid) == 0:
            continue
        ps_list.append(pid)

    ps_list.sort()

    nics = ethtool.get_active_devices()

    for pid in ps_list:
        thread_affinity_list = schedutils.get_affinity(pid)
        if len(thread_affinity_list) <= 4:
            thread_affinity = ",".join(str(a) for a in thread_affinity_list)
        else:
            thread_affinity = ",".join(
                str(hex(a)) for a in procfs.hexbitmask(
                    schedutils.get_affinity(pid), cpuinfo.nr_cpus))
        sched = schedutils.schedstr(schedutils.get_scheduler(pid))[6:]
        rtprio = int(ps[pid]["stat"]["rt_priority"])
        cmd = ps[pid]["stat"]["comm"]
        users = ""
        if cmd[:4] == "IRQ-":
            try:
                users = irqs[cmd[4:]]["users"]
                for u in users:
                    if u in nics:
                        users[users.index(
                            u)] = "%s(%s)" % (u, ethtool.get_module(u))
                users = ",".join(users)
            except:
                users = "Not found in /proc/interrupts!"
        try:
            voluntary_ctxt_switches = int(
                ps[pid]["status"]["voluntary_ctxt_switches"])
            nonvoluntary_ctxt_switches = int(
                ps[pid]["status"]["nonvoluntary_ctxt_switches"])
        except:
            voluntary_ctxt_switches = -1
            nonvoluntary_ctxt_switches = -1
        print "%5d %6s %5d %8s %9d %12s %15s %s" % (
            pid, sched, rtprio, thread_affinity, voluntary_ctxt_switches,
            nonvoluntary_ctxt_switches, cmd, users)
Example #36
0
    def load(self):
        __isdnctrl = '/usr/sbin/userisdnctl'

        l = ethtool.get_active_devices()

        self.activedevicelist = l

        # remove inactive isdn/ppp device
        for i in l:
            nickname = getNickName(self.devicelist, i)
            if getDeviceType(i) == ISDN:
                if os.access(__isdnctrl, os.X_OK):
                    for nick in nickname:
                        if (os.system('%s %s status >& /dev/null' 
                                      % (__isdnctrl,  nickname)) == 0):
                            break
                        else:
                            try:
                                self.activedevicelist.remove(i)
                            except ValueError: # pylint: disable-msg=W0704
                                pass
                            
            elif getDeviceType(i) == MODEM:
                if (os.access('/var/run/ppp-%s.pid' %(i), os.F_OK)):
                    continue
                for nick in nickname:
                    if (os.access('/var/run/ppp-%s.pid' %(nick), os.F_OK)):
                        self.activedevicelist.append(nick)
                        break
                else:
                    self.activedevicelist.remove(i)

#         # check real ppp device
#         for i in xrange(0, 10):
#             if os.access('/var/run/ppp-ppp%s.pid' %(i), os.F_OK):
#                 self.activedevicelist.append('ppp%s' %(i))

#         for pid in glob.glob('/var/run/ppp-*.pid'):
#             pid = pid[13:]
#             pid = pid[:-4]
#             self.activedevicelist.append(pid)

        self.activedevicelist.sort()
Example #37
0
File: rtps.py Project: acmel/ait
def show(ps, cpuinfo, irqs):
	ps_list = []
	for pid in ps.keys():
		if schedutils.get_scheduler(pid) == 0:
			continue
		ps_list.append(pid)

	ps_list.sort()

	nics = ethtool.get_active_devices()

	for pid in ps_list:
		thread_affinity_list = schedutils.get_affinity(pid)
		if len(thread_affinity_list) <= 4:
			thread_affinity = ",".join(str(a) for a in thread_affinity_list)
		else:
			thread_affinity = ",".join(str(hex(a)) for a in procfs.hexbitmask(schedutils.get_affinity(pid), cpuinfo.nr_cpus))
		sched = schedutils.schedstr(schedutils.get_scheduler(pid))[6:]
		rtprio = int(ps[pid]["stat"]["rt_priority"])
		cmd = ps[pid]["stat"]["comm"]
		users = ""
		if cmd[:4] == "IRQ-":
			try:
				users = irqs[cmd[4:]]["users"]
				for u in users:
					if u in nics:
						users[users.index(u)] = "%s(%s)" % (u, ethtool.get_module(u))
				users = ",".join(users)
			except:
				users = "Not found in /proc/interrupts!"
		try:
			voluntary_ctxt_switches = int(ps[pid]["status"]["voluntary_ctxt_switches"])
			nonvoluntary_ctxt_switches = int(ps[pid]["status"]["nonvoluntary_ctxt_switches"])
		except:
			voluntary_ctxt_switches = -1
			nonvoluntary_ctxt_switches = -1
		print "%5d %6s %5d %8s %9d %12s %15s %s" % (pid, sched, rtprio,
							    thread_affinity,
							    voluntary_ctxt_switches,
							    nonvoluntary_ctxt_switches,
							    cmd, users)
Example #38
0
    def LoginVPN(self, server, user, passwd):
        try:
            device = os.popen("pptpsetup --create Account --server %s --username %s --password %s --start" % (server, user, passwd)).readline()
            self.devices = device.split()[-1]

            Setting.setVPNDevice(self.devices)

            try:
                f = open('/etc/ppp/peers/Account', 'a')
                f.write("file /etc/ppp/options.pptp\n")
                f.close()
            except:
                Logger.info('Configuration VPN file failed!') 
        except:
            Util.MessageBox(self, u'VPN连接失败,请联系系统管理员!', u'错误', wx.OK | wx.ICON_ERROR)
            Logger.info('VPN was loginned unsuccessful!')

        os.system("pppd call Account")

        active_interface = []

        i = 0
        while self.devices not in active_interface:
            sleep(1)
            i = i + 1
            if i >= 16:
                Util.MessageBox(self, u'VPN连接失败,请联系系统管理员!', u'错误', wx.OK | wx.ICON_ERROR)
                Logger.info('VPN was loginned unsuccessful!')
                return
            else:
                active_interface = ethtool.get_active_devices()

        os.system("route add -net 0.0.0.0 dev %s" % self.devices)

        Setting.setVPNStatus('%s' % True)
        self.btn_login.SetLabel(u"断开")
        self.DisWidget()
        Setting.save()
        Logger.info('VPN was loginned successful!')
Example #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 as e:
            logger.warn('failed to get ipaddr for device %s: %s' % (dev, e))

    return fqdn
Example #40
0
    def OnVPN(self, event):
        f = open("/etc/ppp/options.pptp")
        bufs = f.readlines()
        f.close()
        if bufs[-1] == "require-mppe-128\n":
            pass
        else:
            f = open("/etc/ppp/options.pptp", 'a') 
            f.write("require-mppe-128\n")  
            f.close()

        active_devices = ethtool.get_active_devices()

        if 'lo' in active_devices:
            active_devices.remove('lo')

        #if Setting.getVPNStatus().lower() == 'true':
        if len(active_devices) < 2:
            Setting.setVPNStatus('%s' % False)
            Setting.save()
        else:
            for i in active_devices:
                if ethtool.get_flags('%s' % i) & ethtool.IFF_POINTOPOINT:
                    Setting.setVPNStatus('%s' % True)
                    Setting.save()
                    break
                elif i == active_devices[-1]:
                    Setting.setVPNStatus('%s' % False)
                    Setting.save()

        dlg = VPNDialog.VPNDialog(self)

        if Setting.getVPNAuto().lower() == 'true' and Setting.getVPNStatus().lower() == 'false':
            dlg.AutoLogin(event)

        if dlg.ShowModal() == wx.ID_OK:
            dlg.save()

        dlg.Destroy()
Example #41
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
Example #42
0
          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))


def main():
    global all_devices

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ("help", ))
    except getopt.GetoptError, err:
        usage()
        print str(err)
        sys.exit(2)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            return

    active_devices = ethtool.get_active_devices()
    for device in active_devices:
        show_config(device)


if __name__ == '__main__':
    main()
Example #43
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
Example #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
Example #45
0
def get_nics():
    global nics
    if nics:
        return nics
    nics = ethtool.get_active_devices()
    return nics
Example #46
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
Example #47
0
          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))

def main():
	global all_devices

	try:
		opts, args = getopt.getopt(sys.argv[1:],
					   "h",
					   ("help",))
	except getopt.GetoptError, err:
		usage()
		print str(err)
		sys.exit(2)

	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
			return

	active_devices = ethtool.get_active_devices()
	for device in active_devices:
		show_config(device)

if __name__ == '__main__':
    main()
 def _has_network(self):
     return [i for i in ethtool.get_active_devices() if i != 'lo']
Example #49
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
Example #50
0
def getIpAddresses():
    "Return a list of the host's IP addresses"
    return filter(None, [getaddr(i) for i in ethtool.get_active_devices()])
Example #51
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
Example #52
0
def _haveNetwork():
    intfs = ethtool.get_active_devices()
    return len(filter(lambda i: i != "lo", intfs)) != 0
Example #53
0
def validLocalHostname():
    try:
        localip = socket.gethostbyname(socket.gethostname())
    except socket.gaierror:
        return False
    return localip in map(ethtool.get_ipaddr, ethtool.get_active_devices())
Example #54
0
 def test_get_interface_info_active(self):
     eis = ethtool.get_interfaces_info(ethtool.get_active_devices())
     for ei in eis:
         self._verify_etherinfo_object(ei)
Example #55
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
Example #56
0
 def test_get_active_devices(self):
     for devname in ethtool.get_active_devices():
         self._functions_accepting_devnames(devname)