最终,我希望能够以以下格式提供输出:
'接口lo向上'
输出为:
[''IF-MIB :: ifDescr.1 = lo','IF-MIB :: ifOperStatus.1 = up']
[''IF-MIB :: ifDescr.2 = eth0','IF-MIB :: ifOperStatus.2 = up']
代码:
from pysnmp.hlapi import *
for errorIndication,errorStatus,errorIndex,varBinds in nextCmd(SnmpEngine(), \
CommunityData('public', mpModel=0), \
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
lexicographicMode=False):
table = []
for varBind in varBinds:
table.append(varBind.prettyPrint().strip())
for i in table:
if i not in table:
table.append(i)
print(table)
for varBind in varBinds:
table.append(varBind.prettyPrint().strip())
for i in table:
if i not in table:
table.append(i)
print(table)
解析的PySNMP ObjectType
由ObjectIdentity
和属于有效SNMP类型的值组成,该值在PySNMP中也称为objectSyntax
。您可以使用Python的标准索引访问这些元素。
在您的循环中,varBinds
是一个列表,其中包含与您传递给ObjectType
的两个ObjectIdentity
对应的完全解析的nextCmd
。您可以解压缩varBinds
以反映每个objectType
,然后索引每个以获取objectSyntax
。调用其prettyPrint
方法时,您将获得我们习惯的人类可读字符串。
from pysnmp.hlapi import *
for _, _, _, varBinds in nextCmd(
SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
lexicographicMode=False):
descr, status = varBinds # unpack the list of resolved objectTypes
iface_name = descr[1].prettyPrint() # access the objectSyntax and get its human-readable form
iface_status = status[1].prettyPrint()
print("Interface {iface} is {status}"
.format(iface=iface_name, status=iface_status))