我試圖使用PySNMP
模塊從Cisco交換機輸出ifTbale
表。表中的PySNMP表字典
這裏是我當前的代碼:
from pysnmp.hlapi import *
for (errorIndication,
errorStatus,
errorIndex,
values) in nextCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('172.20.19.14', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifIndex')),
ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
ObjectType(ObjectIdentity('IF-MIB', 'ifType')),
ObjectType(ObjectIdentity('IF-MIB', 'ifSpeed')),
lexicographicMode=False):
print('======================')
for v in values:
print(str(v))
所以這個工程,因爲它輸出如下:
======================
IF-MIB::ifIndex.10028 = 10028
IF-MIB::ifDescr.10028 = FastEthernet0/28
IF-MIB::ifType.10028 = 'ethernetCsmacd'
IF-MIB::ifSpeed.10028 = 100000000
======================
IF-MIB::ifIndex.10029 = 10029
IF-MIB::ifDescr.10029 = FastEthernet0/29
IF-MIB::ifType.10029 = 'ethernetCsmacd'
IF-MIB::ifSpeed.10029 = 100000000
======================
IF-MIB::ifIndex.10030 = 10030
IF-MIB::ifDescr.10030 = FastEthernet0/30
IF-MIB::ifType.10030 = 'ethernetCsmacd'
IF-MIB::ifSpeed.10030 = 10000000
...
我希望最終變成一個功能這一點,但此刻我想知道如何將它變成嵌套字典。
我想在以下格式的數據: {ifIndex{ifDescr, ifType, ifSpeed}}
這將是這樣的: {10028{ifDescr: 'FastEthernet0/28', ifType: 'ethernetCsmacd', ifSpeed: '100000000'}}
我不能確定如何雖然解決這個問題,因爲我無法建立字典。
編輯: 我已經設法用下面的代碼字典:
print('======================')
raw_dict = {str(v).split('.')[0].split(':')[2]: str(v).split('.')[1].split()[2] for v in values}
print(raw_dict.items())
if_dict = {raw_dict['ifIndex']: {k: v} for k, v in raw_dict.items()}
print(if_dict)
但它不是通過所有的值raw_dict
迭代。
這是輸出:
======================
dict_items([('ifSpeed', '100000000'), ('ifIndex', '10048'), ('ifDescr', 'FastEthernet0/48'), ('ifType', "'ethernetCsmacd'")])
{'10048': {'ifType': "'ethernetCsmacd'"}}
======================
dict_items([('ifSpeed', '1000000000'), ('ifIndex', '10101'), ('ifDescr', 'GigabitEthernet0/1'), ('ifType', "'ethernetCsmacd'")])
{'10101': {'ifType': "'ethernetCsmacd'"}}
======================
dict_items([('ifSpeed', '1000000000'), ('ifIndex', '10102'), ('ifDescr', 'GigabitEthernet0/2'), ('ifType', "'ethernetCsmacd'")])
{'10102': {'ifType': "'ethernetCsmacd'"}}
======================
dict_items([('ifSpeed', '4294967295'), ('ifIndex', '10501'), ('ifDescr', 'Null0'), ('ifType', "'other'")])
{'10501': {'ifType': "'other'"}}