是否可以从此表中提取接口名称和接口状态?

问题描述 投票:1回答:1

最终,我希望能够以以下格式提供输出:

'接口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)
python snmp pysnmp
1个回答
-1
投票

解析的PySNMP ObjectTypeObjectIdentity和属于有效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))
© www.soinside.com 2019 - 2024. All rights reserved.