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

2024-06-30 16:57:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

'接口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)

Tags: inloforiftablemibstripup
1条回答
网友
1楼 · 发布于 2024-06-30 16:57:07

解析的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))

相关问题 更多 >