2017-06-12 764 views
0

我想通過使用python pysnmp模塊來獲取snmp數據。我正在使用命令行來獲取SNMP數據,但現在我想使用pysnmp模塊讀取它。如何使用pysnmp獲取SNMP數據?

SNMP命令 -

snmpwalk -v 1 -c public <ip address>:<port> xyz::pqr 

我用命令等的上方。現在,我想是這樣如下 -

import netsnmp 

def getmac(): 
    oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.17.7.1.2.2.1.2')) 
    res = netsnmp.snmpgetbulk(oid, Version = 1, DestHost='ip', 
          Community='pub') 
    return res 

print getmac() 

我面對錯誤 - 進口netsnmp。沒有模塊netsnmp

任何人都可以給我建議如何可以從snmp服務器與python獲取snmp數據?

回答

1

您似乎正在使用netsnmp模塊而不是pysnmp

如果你想使用pysnmp,然後this example可以幫助:

from pysnmp.hlapi import * 

for (errorIndication, 
    errorStatus, 
    errorIndex, 
    varBinds) in nextCmd(SnmpEngine(), 
          CommunityData('public', mpModel=0), 
          UdpTransportTarget(('demo.snmplabs.com', 161)), 
          ContextData(), 
          ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))): 
    if errorIndication or errorStatus: 
     print(errorIndication or errorStatus) 
     break 
    else: 
     for varBind in varBinds: 
      print(' = '.join([x.prettyPrint() for x in varBind])) 

UPDATE:

上述循環將獲取每次迭代一個OID值。如果您想更有效地提取數據,一種方法是將更多的OID添加到查詢中(以許多ObjectType(...)參數的形式)。

或者您可以切換到GETBULK PDU類型,可以通過將nextCmd呼叫更改爲bulkCmdlike this來完成。

from pysnmp.hlapi import * 

for (errorIndication, 
    errorStatus, 
    errorIndex, 
    varBinds) in bulkCmd(SnmpEngine(), 
     CommunityData('public'), 
     UdpTransportTarget(('demo.snmplabs.com', 161)), 
     ContextData(), 
     0, 25, # fetch up to 25 OIDs one-shot 
     ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))): 
    if errorIndication or errorStatus: 
     print(errorIndication or errorStatus) 
     break 
    else: 
     for varBind in varBinds: 
      print(' = '.join([x.prettyPrint() for x in varBind])) 

請記住,GETBULK命令支持最初是在SNMP v2c中引入的,也就是說您無法通過SNMP v1使用它。

+0

感謝您的回覆。我試過你的代碼片段,但所有數據都沒有得到檢索。任何想法,爲什麼這樣? – kit

+0

@IIya Etingof-我們如何可以一次檢索多個說10個OID數據? – kit

+0

@kit更新我的答案,讓我知道如果這是你所需要的 –