我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用psutil.net_if_addrs()。
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
def get_ips(): """ >>> from psutil._common import snic >>> import mock >>> MOCK = { ... "awdl0": [snic(family=30, address="fe80::3854:80ff:fe54:7bf8%awdl0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)], ... "en0": [snic(family=2, address="192.168.10.200", netmask="255.255.255.0", broadcast="192.168.10.255", ptp=None), ... snic(family=30, address="fe80::6e40:8ff:feac:4f94%en0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)], ... "bridge0": [snic(family=18, address="6e:40:08:ca:60:00", netmask=None, broadcast=None, ptp=None)], ... "lo0": [snic(family=2, address="127.0.0.1", netmask="255.0.0.0", broadcast=None, ptp=None), ... snic(family=30, address="fe80::1%lo0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)]} >>> with mock.patch("psutil.net_if_addrs", side_effect=lambda: MOCK): ... get_ips() ['127.0.0.1/255.0.0.0', '192.168.10.200/255.255.255.0'] """ return sorted(flatten(chain(get_network().values())))
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')
def _get_eth_info(self): eth_info = { 'inner': [], 'outer': [], 'lo': [] } info = psutil.net_if_addrs() for eth, net in info.iteritems(): ip = None for n in net: if n.family == 2 and n.address: ip = n.address break else: continue if ip is None: continue ip_type = self._get_ip_type(ip) eth_info[ip_type].append(eth) return eth_info
def get_netcard(): '''??IP??''' info = psutil.net_if_addrs() for k,v in info.items(): for item in v: if item[0] == 2 and not item[1]=='127.0.0.1' and ':' not in k and '10.' in item[1]: netcard_info = item[1] return netcard_info.replace('.','-')
def get_netcard(self): '''??IP??''' info = psutil.net_if_addrs() for k, v in info.items(): for item in v: if item[0] == 2 and not item[1] == '127.0.0.1' and ':' not in k and '10.' not in item[1]: netcard_info = item[1] return netcard_info.replace('.', '-')
def __get_netcard(self): '''??IP??''' info = psutil.net_if_addrs() for k, v in info.items(): for item in v: if item[0] == 2 and not item[1] == '127.0.0.1' and ':' not in k and '10.' in item[1]: netcard_info = item[1] return netcard_info.replace('.', '-')
def get_network(families=[socket.AF_INET]): """ >>> from psutil._common import snic >>> import mock >>> MOCK = { ... "awdl0": [snic(family=30, address="fe80::3854:80ff:fe54:7bf8%awdl0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)], ... "en0": [snic(family=2, address="192.168.10.200", netmask="255.255.255.0", broadcast="192.168.10.255", ptp=None), ... snic(family=30, address="fe80::6e40:8ff:feac:4f94%en0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)], ... "bridge0": [snic(family=18, address="6e:40:08:ca:60:00", netmask=None, broadcast=None, ptp=None)], ... "lo0": [snic(family=2, address="127.0.0.1", netmask="255.0.0.0", broadcast=None, ptp=None), ... snic(family=30, address="fe80::1%lo0", netmask="ffff:ffff:ffff:ffff::", broadcast=None, ptp=None)]} >>> with mock.patch("psutil.net_if_addrs", side_effect=lambda: MOCK): ... data_inet = get_network([socket.AF_INET]) ... sorted(data_inet.keys()) ['en0', 'lo0'] >>> with mock.patch("psutil.net_if_addrs", side_effect=lambda: MOCK): ... sorted(data_inet.values()) [[u'127.0.0.1/255.0.0.0'], [u'192.168.10.200/255.255.255.0']] >>> with mock.patch("psutil.net_if_addrs", side_effect=lambda: MOCK): ... data_inet6 = get_network([socket.AF_INET6]) ... sorted(flatten(data_inet6.values())) ['fe80::1%lo0/ffff:ffff:ffff:ffff::', 'fe80::3854:80ff:fe54:7bf8%awdl0/ffff:ffff:ffff:ffff::', 'fe80::6e40:8ff:feac:4f94%en0/ffff:ffff:ffff:ffff::'] """ nic = psutil.net_if_addrs() ips = defaultdict(list) # return nic for card, addresses in nic.items(): for address in addresses: if address.family in families: ips[card].append("{0.address}/{0.netmask}".format(address)) return dict(ips) # return flatten([[d.address for d in data if is_valid_ip(d)] for card, data in nic.items()])
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)
def test_net_if_addrs_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
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("^\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))
def update_interfaces(self): self.interfaces.clear() for nic_name, nic_s in psutil.net_if_addrs().items(): for nic in nic_s: # ?????https://github.com/torvalds/linux/blob/5518b69b76680a4f2df96b1deca260059db0c2de/include/linux/socket.h if nic.family == 2: for _nic in nic_s: if _nic.family == 2: self.interfaces[nic_name] = {'ip': _nic.address, 'netmask': _nic.netmask} if _nic.family == 17: self.interfaces[nic_name]['mac'] = _nic.address
def mac_addresses(): mac = get_mac() ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2)) arr = [] for iface in psutil.net_io_counters(pernic=True): try: addr_list = psutil.net_if_addrs() mac = addr_list[str(iface)][2][1] if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str( mac) != '00:00:00:00:00:00': arr.append(mac.lower()) except Exception as e: pass return arr
def interfaces_details(): return psutil.net_if_addrs()
def ip_addresses(): arr = [] for iface in psutil.net_io_counters(pernic=True): ip = psutil.net_if_addrs()[str(iface)][0][1] if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip) and str( ip) != 'localhost' and str(ip) != '127.0.0.1': arr.append(ip) return arr
def find_default_interface(self): """Look through the list of interfaces for the non-loopback interface""" import psutil try: if self.interfaces is None: self.interfaces = {} # Look to see which interfaces are up stats = psutil.net_if_stats() for interface in stats: if interface != 'lo' and interface[:3] != 'ifb' and stats[interface].isup: self.interfaces[interface] = {'packets': 0} if len(self.interfaces) > 1: # See which interfaces have received data cnt = psutil.net_io_counters(True) for interface in cnt: if interface in self.interfaces: self.interfaces[interface]['packets'] = \ cnt[interface].packets_sent + cnt[interface].packets_recv remove = [] for interface in self.interfaces: if self.interfaces[interface]['packets'] == 0: remove.append(interface) if len(remove): for interface in remove: del self.interfaces[interface] if len(self.interfaces) > 1: # Eliminate any with the loopback address remove = [] addresses = psutil.net_if_addrs() for interface in addresses: if interface in self.interfaces: for address in addresses[interface]: if address.address == '127.0.0.1': remove.append(interface) break if len(remove): for interface in remove: del self.interfaces[interface] except Exception: pass
def getAllInterfaces(): def addToArr(array, adapter, ip, mac, device, winguid): if len(mac) == 17: # When no or bad MAC address (e.g. PPP adapter), do not add array.append([adapter, ip, mac, device, winguid]) return array # Returns twodimensional array of interfaces in this sequence for each interface: # [0] = adaptername (e.g. Ethernet or eth0) # [1] = Current IP (e.g. 192.168.0.2) # [2] = Current MAC (e.g. ff:ee:dd:cc:bb:aa) # [3] = Devicename (e.g. Intel 82575LM, Windows only) # [4] = DeviceGUID (e.g. {875F7EDB-CA23-435E-8E9E-DFC9E3314C55}, Windows only) netcard_info = [] info = psutil.net_if_addrs() for k, v in info.items(): ninfo = ['', '', '', '', ''] ninfo[0] = k for item in v: if item[1] == '127.0.0.1': break if item[0] == 2: ninfo[1] = item[1] else: ninfo[2] = item[1] if ninfo[1] == '': continue netcard_info.append(ninfo) return netcard_info ## Listing all NPF adapters and finding the correct one that has the Windows Devicename (\Device\NPF_{GUID})
def get_macid(): ifaces = psutil.net_if_addrs() macs = list() for iface, info in ifaces.items(): if iface == 'lo': continue ipv4_mac = info[-1].address macs.append(ipv4_mac) macs.sort() mac_str = ':'.join(macs) hash_str = hashlib.md5(mac_str.encode('UTF-8')).hexdigest() return hash_str
def get_ips(): ifaces = psutil.net_if_addrs() ips = list() for iface, info in ifaces.items(): if iface == 'lo': continue ip = info[0].address ips.append(ip) return ips
def checkNetVPNV(): """Check if there's a working VPN connection. Verbose.""" # Checking for VPN interfaces INTERFACE_VPN = (config['NETWORK']['INTERFACE_VPN']) print(bc.ENDC + '\t[*] Checking if VPN connection is active' + bc.ENDC) for s in psutil.net_if_addrs(): if any(f in s for f in INTERFACE_VPN.split(',')): print(bc.OKGREEN + '\t[+] Indications of a VPN. Good. Will continue.' + bc.ENDC) return None else: print(bc.WARN + '\t[-] WARN! No indication of a VPN connection on "tun" or "ppp" found.') return 'ERROR'
def get_ip(self): netifaddrs = psutil.net_if_addrs() for interface in netifaddrs: if interface == '': continue for snic in netifaddrs[interface]: if str(snic.family) == '2': if len(snic.address) > 7: self.ip[interface] = snic.address
def main(): stats = psutil.net_if_stats() io_counters = psutil.net_io_counters(pernic=True) for nic, addrs in psutil.net_if_addrs().items(): print("%s:" % (nic)) if nic in stats: st = stats[nic] print(" stats : ", end='') print("speed=%sMB, duplex=%s, mtu=%s, up=%s" % ( st.speed, duplex_map[st.duplex], st.mtu, "yes" if st.isup else "no")) if nic in io_counters: io = io_counters[nic] print(" incoming : ", end='') print("bytes=%s, pkts=%s, errs=%s, drops=%s" % ( io.bytes_recv, io.packets_recv, io.errin, io.dropin)) print(" outgoing : ", end='') print("bytes=%s, pkts=%s, errs=%s, drops=%s" % ( io.bytes_sent, io.packets_sent, io.errout, io.dropout)) for addr in addrs: print(" %-4s" % af_map.get(addr.family, addr.family), end="") print(" address : %s" % addr.address) if addr.broadcast: print(" broadcast : %s" % addr.broadcast) if addr.netmask: print(" netmask : %s" % addr.netmask) if addr.ptp: print(" p2p : %s" % addr.ptp) print("")
def _getDebugData(): try: connections = psutil.net_connections() # You need to be root for OSX except psutil.AccessDenied: connections = None try: addrs = ["* {}: {}".format(key, val) for key, val in psutil.net_if_addrs().items()] except UnicodeDecodeError: addrs = ["INVALID ADDR WITH UNICODE CHARACTERS"] data = """Version: {version} OS: {os} Python: {python} CPU: {cpu} Memory: {memory} Networks: {addrs} Open connections: {connections} Processus: """.format( version=__version__, os=platform.platform(), python=platform.python_version(), memory=psutil.virtual_memory(), cpu=psutil.cpu_times(), connections=connections, addrs="\n".join(addrs) ) for proc in psutil.process_iter(): try: psinfo = proc.as_dict(attrs=["name", "exe"]) data += "* {} {}\n".format(psinfo["name"], psinfo["exe"]) except psutil.NoSuchProcess: pass data += "\n\nProjects" for project in Controller.instance().projects.values(): data += "\n\nProject name: {}\nProject ID: {}\n".format(project.name, project.id) for link in project.links.values(): data += "Link {}: {}".format(link.id, link.debug_link_data) return data
def get_eth_info(self): """ ????? 1. ??bond???bond0 2. ???????eth0:1 3. ?ip???eth0(1.1.1.1,2.2.2.2) """ data = [] addrs = psutil.net_if_addrs() stats = psutil.net_if_stats() for name, entries in addrs.iteritems(): eth = { 'name': name, 'mac': '00:00:00:00:00:00', 'ip': '', 'mask': '', 'broadcast': '', 'status': 'Unknown', 'speed': 0 } try: # windows??? eth['name'] = name.decode('gbk') except: eth['name'] = name if name in stats: eth['status'] = 'Active' if int(stats[name].isup) else 'Inactive' eth['speed'] = stats[name].speed for entry in entries: if entry.family == psutil.AF_LINK: eth['mac'] = entry.address.upper() elif entry.family == socket.AF_INET: if eth['ip']:# ??????ip???????????? data.append(copy.deepcopy(eth)) eth['ip'] = entry.address eth['mask'] = entry.netmask eth['broadcast'] = entry.broadcast else: # ????IPV6 continue data.append(eth) # ???????????????mac?????00:00:00:00:00:00????????????":" for item in data: # ?????? if ':' not in item['name']: continue # ???mac?????????????????????":"???? if item['mac'] != '00:00:00:00:00:00': continue name = item['name'].rsplit(':', 1)[0] for iitem in data: if name == iitem['name']: item['mac'] = iitem['mac'] break data.sort(key=lambda x: x['name']) return data
def test_net_if_addrs(self): nics = psutil.net_if_addrs() assert nics, nics nic_stats = psutil.net_if_stats() # Not reliable on all platforms (net_if_addrs() reports more # interfaces). # self.assertEqual(sorted(nics.keys()), # sorted(psutil.net_io_counters(pernic=True).keys())) families = set([socket.AF_INET, AF_INET6, psutil.AF_LINK]) for nic, addrs in nics.items(): self.assertIsInstance(nic, (str, unicode)) self.assertEqual(len(set(addrs)), len(addrs)) for addr in addrs: self.assertIsInstance(addr.family, int) self.assertIsInstance(addr.address, str) self.assertIsInstance(addr.netmask, (str, type(None))) self.assertIsInstance(addr.broadcast, (str, type(None))) self.assertIn(addr.family, families) if sys.version_info >= (3, 4): self.assertIsInstance(addr.family, enum.IntEnum) if nic_stats[nic].isup: # Do not test binding to addresses of interfaces # that are down if addr.family == socket.AF_INET: s = socket.socket(addr.family) with contextlib.closing(s): s.bind((addr.address, 0)) elif addr.family == socket.AF_INET6: info = socket.getaddrinfo( addr.address, 0, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] af, socktype, proto, canonname, sa = info s = socket.socket(af, socktype, proto) with contextlib.closing(s): s.bind(sa) for ip in (addr.address, addr.netmask, addr.broadcast, addr.ptp): if ip is not None: # TODO: skip AF_INET6 for now because I get: # AddressValueError: Only hex digits permitted in # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0' if addr.family != AF_INET6: check_net_address(ip, addr.family) # broadcast and ptp addresses are mutually exclusive if addr.broadcast: self.assertIsNone(addr.ptp) elif addr.ptp: self.assertIsNone(addr.broadcast) if BSD or OSX or SUNOS: if hasattr(socket, "AF_LINK"): self.assertEqual(psutil.AF_LINK, socket.AF_LINK) elif LINUX: self.assertEqual(psutil.AF_LINK, socket.AF_PACKET) elif WINDOWS: self.assertEqual(psutil.AF_LINK, -1)
def update(self): """Get the latest system information.""" import psutil if self.type == 'disk_use_percent': self._state = psutil.disk_usage(self.argument).percent elif self.type == 'disk_use': self._state = round(psutil.disk_usage(self.argument).used / 1024**3, 1) elif self.type == 'disk_free': self._state = round(psutil.disk_usage(self.argument).free / 1024**3, 1) elif self.type == 'memory_use_percent': self._state = psutil.virtual_memory().percent elif self.type == 'memory_use': self._state = round((psutil.virtual_memory().total - psutil.virtual_memory().available) / 1024**2, 1) elif self.type == 'memory_free': self._state = round(psutil.virtual_memory().available / 1024**2, 1) elif self.type == 'swap_use_percent': self._state = psutil.swap_memory().percent elif self.type == 'swap_use': self._state = round(psutil.swap_memory().used / 1024**3, 1) elif self.type == 'swap_free': self._state = round(psutil.swap_memory().free / 1024**3, 1) elif self.type == 'processor_use': self._state = round(psutil.cpu_percent(interval=None)) elif self.type == 'process': if any(self.argument in l.name() for l in psutil.process_iter()): self._state = STATE_ON else: self._state = STATE_OFF elif self.type == 'network_out' or self.type == 'network_in': counters = psutil.net_io_counters(pernic=True) if self.argument in counters: counter = counters[self.argument][IO_COUNTER[self.type]] self._state = round(counter / 1024**2, 1) else: self._state = STATE_UNKNOWN elif self.type == 'packets_out' or self.type == 'packets_in': counters = psutil.net_io_counters(pernic=True) if self.argument in counters: self._state = counters[self.argument][IO_COUNTER[self.type]] else: self._state = STATE_UNKNOWN elif self.type == 'ipv4_address' or self.type == 'ipv6_address': addresses = psutil.net_if_addrs() if self.argument in addresses: self._state = addresses[self.argument][IF_ADDRS[self.type]][1] else: self._state = STATE_UNKNOWN elif self.type == 'last_boot': self._state = dt_util.as_local( dt_util.utc_from_timestamp(psutil.boot_time()) ).date().isoformat() elif self.type == 'since_last_boot': self._state = dt_util.utcnow() - dt_util.utc_from_timestamp( psutil.boot_time())
def test_net_if_addrs(self): nics = psutil.net_if_addrs() assert nics, nics nic_stats = psutil.net_if_stats() # Not reliable on all platforms (net_if_addrs() reports more # interfaces). # self.assertEqual(sorted(nics.keys()), # sorted(psutil.net_io_counters(pernic=True).keys())) families = set([socket.AF_INET, AF_INET6, psutil.AF_LINK]) for nic, addrs in nics.items(): self.assertEqual(len(set(addrs)), len(addrs)) for addr in addrs: self.assertIsInstance(addr.family, int) self.assertIsInstance(addr.address, str) self.assertIsInstance(addr.netmask, (str, type(None))) self.assertIsInstance(addr.broadcast, (str, type(None))) self.assertIn(addr.family, families) if sys.version_info >= (3, 4): self.assertIsInstance(addr.family, enum.IntEnum) if nic_stats[nic].isup: # Do not test binding to addresses of interfaces # that are down if addr.family == socket.AF_INET: s = socket.socket(addr.family) with contextlib.closing(s): s.bind((addr.address, 0)) elif addr.family == socket.AF_INET6: info = socket.getaddrinfo( addr.address, 0, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] af, socktype, proto, canonname, sa = info s = socket.socket(af, socktype, proto) with contextlib.closing(s): s.bind(sa) for ip in (addr.address, addr.netmask, addr.broadcast, addr.ptp): if ip is not None: # TODO: skip AF_INET6 for now because I get: # AddressValueError: Only hex digits permitted in # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0' if addr.family != AF_INET6: check_net_address(ip, addr.family) # broadcast and ptp addresses are mutually exclusive if addr.broadcast: self.assertIsNone(addr.ptp) elif addr.ptp: self.assertIsNone(addr.broadcast) if BSD or OSX or SUNOS: if hasattr(socket, "AF_LINK"): self.assertEqual(psutil.AF_LINK, socket.AF_LINK) elif LINUX: self.assertEqual(psutil.AF_LINK, socket.AF_PACKET) elif WINDOWS: self.assertEqual(psutil.AF_LINK, -1)