是否可以从这个 table 中提取接口名称和接口状态?

Is it possible to pull the interface name and interface status from this table?

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

'Interface lo is up'

输出为:

['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 ObjectTypeObjectIdentity 和属于有效 SNMP 类型的值组成,在 PySNMP 中也称为 objectSyntax。您可以使用 Python 的标准索引访问这些元素。

在你的循环中,varBinds 是一个列表,由完全解析的 ObjectType 组成,对应于你传递给 nextCmd 的两个 ObjectIdentity。您可以解压缩 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))