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
python类net_if_addrs()的实例源码
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 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 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_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 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 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 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("")