我正在尝试构造一个陷阱侦听器对象,该对象将在与我所运行的对象相同的并行进程中启动和运行。
下面的代码中的陷阱侦听器部分经过了很好的调试,当我在类之外构造Process时,它便完成了它的工作。问题是我希望能够“隐藏”与侦听器和流程定义相关的所有代码。
这样,我将能够在我的一个测试脚本中构造Trap Listener,而不会增加太多开销。
陷阱侦听器类:
try:
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, view, compiler, rfc1902, error
from pysnmp import debug
except ImportError:
print("IMPORT ERROR")
from multiprocessing import Process, Queue
class Trap_Listener():
def __init__(self):
self.PORT = 162
self.ip_type = '4'
self.trap_count = 0
self.snmpEngine = engine.SnmpEngine()
self.COMMUNITYSTRING = 'automation'
config.addV1System(self.snmpEngine, self.COMMUNITYSTRING, self.COMMUNITYSTRING)
self.queue = Queue()
self.Parallel_Process = Process(target=self.run)
def run(self):
ntfrcv.NotificationReceiver(self.snmpEngine, self.cbFun)
self.add_transport(self.snmpEngine, self.PORT, self.ip_type)
self.snmpEngine.transportDispatcher.jobStarted(1)
try:
print("Trap Listener started .....")
print("To Stop Press Ctrl+c")
print("\n")
self.snmpEngine.transportDispatcher.runDispatcher()
except KeyboardInterrupt:
print('Trap Listener was stopped manually')
self.snmpEngine.transportDispatcher.closeDispatcher()
except:
self.snmpEngine.transportDispatcher.closeDispatcher()
raise
self.Parallel_Process.daemon = True
self.Parallel_Process.start()
def stop(self):
print('Trap Listener was stopped manually')
self.snmpEngine.transportDispatcher.closeDispatcher()
self.Parallel_Process.join()
def get_all_traps(self):
traps_list = []
while not self.queue.empty():
traps_list.append(self.queue.get())
return traps_list
def add_transport(self, snmpEngine, PORT, ip_type):
from sys import exit
try:
if ip_type == '6':
config.addTransport(snmpEngine, udp.domainName,
udp6.Udp6SocketTransport().openServerMode(('::', int(PORT)))
)
else:
config.addTransport(
snmpEngine,
udp.domainName,
udp.UdpTransport().openServerMode(('', int(PORT)))
)
except:
print('UDP Port 162 is blocked')
exit()
def cbFun(self, varBinds):
self.trap_count += 1
self.queue.put(varBinds)
现在,当我尝试与正在运行的脚本并行使用此侦听器时,它似乎阻塞了主脚本。意思是,我在脚本中执行的所有可能导致陷阱生成的步骤都没有执行,并且系统正在等待陷阱
我正在使用的脚本如下所示:
listener = Trap_Listener()
listener.run()
'''
# Doing Some actions that cause traps to
# be generated
'''
traps_list = listener.get_all_traps()
for trap in traps_list:
for oid, value in trap:
print(oid, value)
listener.stop()
我在做什么错?为什么侦听器不并行运行?