查找网络信息

时间:2018-03-04 18:24:59

标签: python python-2.7

我试图用Python查找我的计算机网络信息,并使用psutil。我得到的结果如下:

{'Local Area Connection* 2': [snic(family=-1, address='34-F3-9A-4C-D0-C5', netmask=None, broadcast=None, ptp=None), snic(family=2, address='169.254.189.147', netmask='255.255.0.0', broadcast=None, ptp=None), snic(family=23, address='fe80::b83c:382a:1976:bd93', netmask=None, broadcast=None, ptp=None)], 'Ethernet': [snic(family=-1, address='C8-5B-76-AC-B7-BC', netmask=None, broadcast=None, ptp=None), snic(family=2, address='10.164.200.11', netmask='255.255.255.0', broadcast=None, ptp=None), snic(family=23, address='fe80::28db:c0b:3d58:9aba', netmask=None, broadcast=None, ptp=None)], 'Wi-Fi': [snic(family=-1, address='34-F3-9A-4C-D0-C4', netmask=None, broadcast=None, ptp=None), snic(family=2, address='192.168.1.102', netmask='255.255.255.0', broadcast=None, ptp=None), snic(family=23, address='fe80::5c61:43a3:f2d6:c994', netmask=None, broadcast=None, ptp=None)], 'Local Area Connection* 4': [snic(family=-1, address='00-00-00-00-00-00-00-E0', netmask=None, broadcast=None, ptp=None), snic(family=23, address='2001:0:9d38:90d7:1093:131:3f57:fe99', netmask=None, broadcast=None, ptp=None), snic(family=23, address='fe80::1093:131:3f57:fe99', netmask=None, broadcast=None, ptp=None)], 'Loopback Pseudo-Interface 1': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snic(family=23, address='::1', netmask=None, broadcast=None, ptp=None)]}

我尝试获取连接名称和相应的ip,netmask,mac地址。但我无法得到它。当我使用for循环时,这个dict的密钥只是我得到的东西:

def NETWORK():
netinfo = psutil.net_if_addrs()
for connection_name in netinfo :
    print connection_name

结果是:

Local Area Connection* 2
Ethernet
Wi-Fi
Local Area Connection* 4
Loopback Pseudo-Interface 1
None

我尝试通过这种方式访问​​这些密钥的价值但不成功:

print netinfo['address']
print connection_name['address']
print connection_name.address()

请告诉我如何访问此dict并获取连接名称和相应的ip,netmask,mac地址。 非常感谢

1 个答案:

答案 0 :(得分:0)

这是一个dict格式输出。因此,您需要按键访问值。

当你运行命令时,你会得到' en0' ' EN1'等作为键。

>>> out = psutil.net_if_addrs()

out将是一个词典。因此,为了获得' en0' ,使用

>>>out['en0']

这将给出snic个对象的列表。您可以循环遍历它们并获取如下数据

>>> for a in out['en0']:
...     print(a.address)

这将给出各种地址。 要访问其他关键信息,请使用a.netmask