pysnmp: AttributeError: объект 'модуль' не имеет атрибута 'NotificationOriginator' - PullRequest
0 голосов
/ 18 июня 2020

Я работаю над pysnmp, где мой сценарий действует как прослушиватель и сервер пересылки SNMP. Я могу получать ловушки SNMP, и я могу видеть MIB. Я получаю сообщение об ошибке функции sendPdu ntforg.NotificationOriginator () . Я использую python 2 на centos.

вот фрагмент ошибки:

Traceback (most recent call last):
File "/tmp/akhil.py", line 65, in <module>
snmp_engine.transportDispatcher.runDispatcher()
File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 50, in runDispatcher
pysnmp.error.PySnmpError: poll error: Traceback (most recent call last):
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 46, in runDispatcher
    use_poll=True, map=self.__sockMap, count=1)
;  File "/usr/lib64/python2.7/asyncore.py", line 220, in loop
    poll_fun(timeout, map)
;  File "/usr/lib64/python2.7/asyncore.py", line 201, in poll2
    readwrite(obj, flags)
;  File "/usr/lib64/python2.7/asyncore.py", line 123, in readwrite
    obj.handle_error()
;  File "/usr/lib64/python2.7/asyncore.py", line 108, in readwrite
    obj.handle_read_event()
;  File "/usr/lib64/python2.7/asyncore.py", line 449, in handle_read_event
    self.handle_read()
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dgram/base.py", line 170, in handle_read
    self._cbFun(self, transportAddress, incomingMessage)
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/base.py", line 70, in _cbFun
    self, transportDomain, transportAddress, incomingMessage
;  File "build/bdist.linux-x86_64/egg/pysnmp/entity/engine.py", line 152, in __receiveMessageCbFun
    self, transportDomain, transportAddress, wholeMsg
;  File "build/bdist.linux-x86_64/egg/pysnmp/proto/rfc3412.py", line 433, in receiveMessage
    PDU, maxSizeResponseScopedPDU, stateReference)
;  File "build/bdist.linux-x86_64/egg/pysnmp/entity/rfc3413/ntfrcv.py", line 115, in processPdu
    contextName, varBinds, self.__cbCtx)
;  File "/tmp/akhil.py", line 54, in cbFun
    ntf_org = ntforg.NotificationOriginator()
;AttributeError: 'module' object has no attribute 'NotificationOriginator'
caused by <type 'exceptions.AttributeError'>: 'module' object has no attribute 'NotificationOriginator'
e here

Мой код:

from pysmi.codegen import PySnmpCodeGen
from pysmi.parser import SmiStarParser
from pysmi.reader import FileReader
from pysmi.searcher import PyFileSearcher, PyPackageSearcher, StubSearcher
from pysmi.writer import PyFileWriter
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.carrier.error import CarrierError
from pysnmp.entity import config, engine
from pysnmp.entity.rfc3413 import ntforg, ntfrcv
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.hlapi import *
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, compiler, view
from pysnmp.smi.error import MibNotFoundError
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType

# snmpTrapAddress, SCALAR, not-accessible, IpAddress, 1.3.6.1.6.3.18.1.3.0

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmp_engine = engine.SnmpEngine()


# UDP over IPv4
config.addTransport(
    snmp_engine,
    udp.domainName,
    udp.UdpTransport().openServerMode(("0.0.0.0", 162))
)

config.addTransport(
        snmp_engine,
        udp.domainName + (2,),
        udp.UdpTransport().openClientMode()
)

# SNMPv1/2c setup
config.addV1System(snmp_engine, "my-area", "public")

config.addTargetParams(snmp_engine, "distant_agent_auth", "public", "noAuthNoPriv", 1)

config.addTargetAddr(snmp_engine, "distant_agent", udp.domainName + (2,),("100.80.97.21", 162), "distant_agent_auth", retryCount=0)

def cbFun(snmp_engine, state_reference, context_engine_id, context_name, var_binds, cb_ctx):
    execContext = snmp_engine.observer.getExecutionContext("rfc3412.receiveMessage:request")
    trap_pdu = v2c.TrapPDU()
    v2c.apiTrapPDU.setDefaults(trap_pdu)
    v2c.apiTrapPDU.setVarBinds(trap_pdu, var_binds)
    source_ip_address = execContext["transportAddress"][0]
    print "got traps from : {}".format(source_ip_address)
    var_binds_dict = {name.prettyPrint(): None if val.prettyPrint() == "" else val.prettyPrint() for name, val in var_binds}
    print var_binds_dict
    print "sending traps to destination 100.80.97.21"
    ntf_org = ntforg.NotificationOriginator()
    ntf_org.sendPdu(snmp_engine, "distant_agent", None, "", trap_pdu)


# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmp_engine, cbFun)

snmp_engine.transportDispatcher.jobStarted(1)  # this job would never finish

# Run I/O dispatcher which would receive queries and send confirmations
try:
    snmp_engine.transportDispatcher.runDispatcher()
except:
    snmp_engine.transportDispatcher.closeDispatcher()
    raise
finally:
    snmp_engine.transportDispatcher.closeDispatcher()
    snmp_engine.transportDispatcher.jobFinished(1)

сведения о версии:

>>> pysnmp.__version__
'4.4.9'

>>> pysmi.__version__
'0.3.4'

Я что-нибудь упустил?

1 Ответ

0 голосов
/ 22 июня 2020

Я точно не знаю, «почему», но если вы хотите импортировать что-то из hlapi, попробуйте импортировать указанный модуль c, который вы хотите использовать. Таким образом, избегайте использования from pysnmp.hlapi import *. Так что, если вы удалите этот фрагмент кода, ваша система, вероятно, будет работать правильно.

...