当前位置: 首页>>代码示例>>Python>>正文


Python psutil.net_if_addrs方法代码示例

本文整理汇总了Python中psutil.net_if_addrs方法的典型用法代码示例。如果您正苦于以下问题:Python psutil.net_if_addrs方法的具体用法?Python psutil.net_if_addrs怎么用?Python psutil.net_if_addrs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在psutil的用法示例。


在下文中一共展示了psutil.net_if_addrs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_ips

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def test_ips(self):
        for name, addrs in psutil.net_if_addrs().items():
            for addr in addrs:
                if addr.family == psutil.AF_LINK:
                    self.assertEqual(addr.address, get_mac_address(name))
                elif addr.family == socket.AF_INET:
                    self.assertEqual(addr.address, get_ipv4_address(name))
                # TODO: test for AF_INET6 family

    # XXX - not reliable when having virtual NICs installed by Docker.
    # @unittest.skipIf(not which('ip'), "'ip' utility not available")
    # @unittest.skipIf(TRAVIS, "skipped on Travis")
    # def test_net_if_names(self):
    #     out = sh("ip addr").strip()
    #     nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
    #     found = 0
    #     for line in out.split('\n'):
    #         line = line.strip()
    #         if re.search(r"^\d+:", line):
    #             found += 1
    #             name = line.split(':')[1].strip()
    #             self.assertIn(name, nics)
    #     self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
    #         pprint.pformat(nics), out)) 
开发者ID:giampaolo,项目名称:psutil,代码行数:26,代码来源:test_linux.py

示例2: getNetworkInfo

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def getNetworkInfo(cls):
        interfaces = {}

        stats = psutil.net_if_stats()
        for key, value in six.iteritems(stats):
            interfaces[key] = value.__dict__
            interfaces[key]['addresses'] = []
            interfaces[key]['io_counters'] = None

        addresses = psutil.net_if_addrs()
        for key, value in six.iteritems(addresses):
            if key not in interfaces:
                continue

            for addr in value:
                interfaces[key]['addresses'].append(addr.__dict__)

        traffic = psutil.net_io_counters(pernic=True)
        for key, value in six.iteritems(traffic):
            if key not in interfaces:
                continue

            interfaces[key]['io_counters'] = value.__dict__

        return interfaces 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:27,代码来源:system_status.py

示例3: test_net_if_addrs_mac_null_bytes

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def test_net_if_addrs_mac_null_bytes(self):
        # Simulate that the underlying C function returns an incomplete
        # MAC address. psutil is supposed to fill it with null bytes.
        # https://github.com/giampaolo/psutil/issues/786
        if POSIX:
            ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
        else:
            ret = [('em1', -1, '06-3d-29', None, None, None)]
        with mock.patch('psutil._psplatform.net_if_addrs',
                        return_value=ret) as m:
            addr = psutil.net_if_addrs()['em1'][0]
            assert m.called
            if POSIX:
                self.assertEqual(addr.address, '06:3d:29:00:00:00')
            else:
                self.assertEqual(addr.address, '06-3d-29-00-00-00') 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:18,代码来源:test_system.py

示例4: get_mac_address_of_interface

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def get_mac_address_of_interface(interface):
    """
    :param interface: The friendly name of a network interface
    :return: the MAC address associated with that interface
    """
    for k,v in psutil.net_if_addrs().items():
        if interface == k:
            for item in v:
                try:
                    if item.family == socket.AF_LINK:
                        return item.address
                except AttributeError:
                    # Linux
                    if item.family == socket.AF_PACKET:
                        return item.address
    return None 
开发者ID:PacketTotal,项目名称:HoneyBot,代码行数:18,代码来源:utils.py

示例5: network_status

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def network_status(response):
	interfaces = psutil.net_if_addrs()

	for name, addrs in interfaces.items():
		key = common.decode2utf8(name) if common.is_python2x() else name
		status = {
			"ipv4" : "-",
			"ipv6" : "-",
			"mac" : "-"
		}
		
		for addr in addrs:
			if addr.family == socket.AF_INET:
				status["ipv4"] = addr.address

			if addr.family == socket.AF_INET6:
				status["ipv6"] = addr.address

			if addr.family == psutil.AF_LINK:
				status["mac"] = addr.address

		response["nic"][key] = status 
开发者ID:turingsec,项目名称:marsnake,代码行数:24,代码来源:network_status.py

示例6: getNetiAddrInfo

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def getNetiAddrInfo(self):
        neti_list = []
        ipv4_list = []
        ipv6_list = []
        id_neti_list = []
        result_list = []
        neti_dict = psutil.net_if_addrs()
        for neti in neti_dict:
            neti_list.append(neti)
            id_neti_list.append('NETI-{}-{}'.format(self.os_id, neti))
            snic_list = neti_dict[neti]
            for snic in snic_list:
                if snic.family.name == 'AF_INET':
                    ipv4_list.append(snic.address)

                elif snic.family.name == 'AF_INET6':
                    ipv6_list.append(re.sub('%.*$', '', snic.address))

        result = [','.join(neti_list), ','.join(ipv4_list + ipv6_list), ','.join(id_neti_list)]
        return(result) 
开发者ID:kylechenoO,项目名称:AIOPS_PLATFORM,代码行数:22,代码来源:OS.py

示例7: check

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def check(self) -> Optional[str]:
        own_addresses = [
            (item.family, item.address.split("%")[0])
            for sublist in psutil.net_if_addrs().values()
            for item in sublist
        ]
        connected = [
            c.laddr[1]
            for c in psutil.net_connections()
            if (
                (c.family, c.laddr[0]) in own_addresses
                and c.status == "ESTABLISHED"
                and c.laddr[1] in self._ports
            )
        ]
        if connected:
            return "Ports {} are connected".format(connected)
        else:
            return None 
开发者ID:languitar,项目名称:autosuspend,代码行数:21,代码来源:activity.py

示例8: create

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def create(
        cls, name: str, config: configparser.SectionProxy,
    ) -> "NetworkBandwidth":
        try:
            interfaces = config["interfaces"].split(",")
            interfaces = [i.strip() for i in interfaces if i.strip()]
            if not interfaces:
                raise ConfigurationError("No interfaces configured")
            host_interfaces = psutil.net_if_addrs().keys()
            for interface in interfaces:
                if interface not in host_interfaces:
                    raise ConfigurationError(
                        "Network interface {} does not exist".format(interface)
                    )
            threshold_send = config.getfloat("threshold_send", fallback=100)
            threshold_receive = config.getfloat("threshold_receive", fallback=100)
            return cls(name, interfaces, threshold_send, threshold_receive)
        except KeyError as error:
            raise ConfigurationError(
                "Missing configuration key: {}".format(error)
            ) from error
        except ValueError as error:
            raise ConfigurationError(
                "Threshold in wrong format: {}".format(error)
            ) from error 
开发者ID:languitar,项目名称:autosuspend,代码行数:27,代码来源:activity.py

示例9: get_netinfo

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def get_netinfo(exclude_down=True):
	netinfo={}
	for ifc, snics in psutil.net_if_addrs().items():
		if ifc=="lo":
			continue
		for snic in snics:
			if snic.family == socket.AF_INET:
				netinfo[ifc]=snic
		if ifc not in netinfo:
			c=0
			for snic in snics:
				if snic.family == socket.AF_INET6:
					c+=1
			if c>=2:
				netinfo[ifc]=snic
		if ifc not in netinfo and not exclude_down:
			netinfo[ifc]=None
	return netinfo 
开发者ID:zynthian,项目名称:zynthian-ui,代码行数:20,代码来源:zynthian_config.py

示例10: get_network

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def get_network():
    network = psutil.net_io_counters(pernic=True)
    ifaces = psutil.net_if_addrs()
    networks = list()
    for k, v in ifaces.items():
        ip = v[0].address
        data = network[k]
        ifnet = dict()
        ifnet['ip'] = ip
        ifnet['iface'] = k
        ifnet['sent'] = '%.2fMB' % (data.bytes_sent/1024/1024)
        ifnet['recv'] = '%.2fMB' % (data.bytes_recv/1024/1024)
        ifnet['packets_sent'] = data.packets_sent
        ifnet['packets_recv'] = data.packets_recv
        ifnet['errin'] = data.errin
        ifnet['errout'] = data.errout
        ifnet['dropin'] = data.dropin
        ifnet['dropout'] = data.dropout
        networks.append(ifnet)
    return networks 
开发者ID:HatBoy,项目名称:RTask,代码行数:22,代码来源:sysinfo.py

示例11: get_all_addresses

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def get_all_addresses() -> Set[str]:
    """ Uses a combination of methods to determine possible addresses.

    Returns:
         list of addresses as strings
    """
    net_interfaces = psutil.net_if_addrs()

    s_addresses = set()
    for interface in net_interfaces:
        try:
            s_addresses.add(address_by_interface(interface))
        except Exception:
            logger.exception("Ignoring failure to fetch address from interface {}".format(interface))
            pass

    resolution_functions = [address_by_hostname, address_by_route, address_by_query]  # type: List[Callable[[], str]]
    for f in resolution_functions:
        try:
            s_addresses.add(f())
        except Exception:
            logger.exception("Ignoring an address finder exception")

    return s_addresses 
开发者ID:Parsl,项目名称:parsl,代码行数:26,代码来源:addresses.py

示例12: get_net_if

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def get_net_if():
    return [(key, value[0].address) for key, value in net_if_addrs().items()
            if value[0].family == AddressFamily.AF_INET and key != 'lo'][0] 
开发者ID:criteo,项目名称:tf-yarn,代码行数:5,代码来源:gloo_allred_task.py

示例13: update_network_interfaces

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def update_network_interfaces(self):
        self.ui.comboBox_Interface.clear()
        self.net_if = psutil.net_if_addrs()
        net_if_stats = psutil.net_if_stats()

        net_names = list(self.net_if.keys())

        for if_name in net_names:
            if not net_if_stats[if_name].isup:
                self.net_if.pop(if_name, None)
            else:
                self.ui.comboBox_Interface.addItem(if_name)

        interface_idx = self.config.get('Interface', 0)

        if interface_idx >= self.ui.comboBox_Interface.count():
            self.ui.comboBox_Interface.setCurrentIndex(0)
        else:
            self.ui.comboBox_Interface.setCurrentIndex(interface_idx)

        current_interface = self.ui.comboBox_Interface.currentText()
        self.config['Interface'] = self.ui.comboBox_Interface.currentIndex()

        for snicaddr in self.net_if[current_interface]:
            if snicaddr.family == socket.AF_INET:
                ipv4_add = snicaddr.address
                break
            else:
                ipv4_add = '0.0.0.0'

        self.ui.label_LocalIP.setText(ipv4_add)

        self.save_config() 
开发者ID:rookiepeng,项目名称:socket-test,代码行数:35,代码来源:socket_test.py

示例14: test_net_if_addrs

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def test_net_if_addrs(self):
        # Note: verified that on Windows this was a false positive.
        self.execute(psutil.net_if_addrs,
                     tolerance_=80 * 1024 if WINDOWS else None) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:6,代码来源:test_memory_leaks.py

示例15: test_net_if_addrs_names

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import net_if_addrs [as 别名]
def test_net_if_addrs_names(self):
        out = sh('/etc/ifconfig -l')
        ifconfig_names = set(out.split())
        psutil_names = set(psutil.net_if_addrs().keys())
        self.assertSetEqual(ifconfig_names, psutil_names) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:7,代码来源:test_aix.py


注:本文中的psutil.net_if_addrs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。