簡體   English   中英

合並各種SNMP事務並將每個OID和結果分配給唯一變量以進行進一步處理

[英]Consolidating various SNMP transactions and assigning the OID and result of each to unique variables for further processing

我正在嘗試編寫具有許多SNMP事務的代碼,一些事務可以捆綁到PySNMP的相同getCmd()函數中。 話雖如此,我不打算立即打印SNMP事務結果的值,有時需要進一步處理。 IE:拆箱。 捆綁兩個SNMP事務如下所示:

from pysnmp.hlapi import *

errorIndication, errorStatus, errorIndex, varBinds = next(
    getCmd(SnmpEngine(),
           CommunityData('somePasswd'),
           UdpTransportTarget(('somedev.example.com', 161)),
           ContextData(),
           #One MIB
           ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', '0')),
           #Second MIB
           ObjectType(ObjectIdentity('CISCO-CDP-MIB', 'cdpCacheAddress', 1,1)),
           lookupNames=True,
           lookupValues=True,
))

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (errorStatus.prettyPrint(),
                        errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    for varBind in varBinds:
        print(' = '.join([x.prettyPrint() for x in varBind]))

我想將特定MIB的值分配給變量的方式,我必須在上一個for循環下放置一個if..elseif語句,以比較要查找的MIB的值到oid Iterables的當前值(我認為是該術語)。 因此,我的代碼將更改為:

for oid, value in varBinds:
    if oid == 'SNMPv2-MIB::sysName.0':
        #take specific actions
    elif oid == 'CISCO-CDP-MIB::cdpCacheAddress.1.1'
        #take different actions

我認為這可能是一種處理方式,但是我有兩個問題:

  1. 這是處理多個SNMP事務的有效方法嗎?

  2. 使每個SNMP Get事務保持獨立對代碼而言是否更好?

  3. 執行以下操作時,我的OID會轉換為對人類友好的MIBS:

      for varBind in varBinds print(' = '.join([x.prettyPrint() for x in varBind])) 

但是以下內容使我感到丑陋:

     for oid, value in varBinds:
             print("oid:",oid,"Value",value):

通過將oid和value傳遞給我的for循環,我如何最終得到一個人類友好的mib而不是丑陋的oid?

更新:

像這樣將.loadMibs傳遞給ObjectIdentity :在打印oidvalueObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', '0').loadMibs('SNMPv2-MIB'))仍然給我一個OID: for oid, value in varBinds:

我認為一次提取兩個托管對象(這是SNMP的說法)是正確的方法。 這是通過高級SNMP API獲取數據的最有效方法。

一旦獲得兩個托管對象作為響應,就可以遍歷它們並采取相應的措施-這就是您的代碼似乎要做的。 我個人在那里看不到任何問題。

要解決針對MIB收到的變量綁定(代表SNMP管理的對象),您只需在它們上調用.prettyPrint()

for oid, value in varBinds:
    print("Name: ", oid.prettyPrint(), "Value: ", value.prettyPrint()):

如果要基於OID值分支處理,最有效的方法是比較這些難看的OID:

for oid, value in varBinds:
    if oid == (1, 3, 6, 1, 2, 1, 1, 5, 0):  # 'SNMPv2-MIB::sysName.0':
        #take specific actions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM