PYSNMP停止并重新启动陷阱接收器

时间:2014-02-20 20:34:27

标签: pysnmp

我正在尝试创建一个pysnmp守护进程。我希望能够启动,停止和重新启动运行守护程序的线程。我在清理套接字,通知接收器和传输调度程序时遇到问题。

我正在使用pysnmp v1 / 2c陷阱接收器

class trapReceiverThread(threading.Thread):
def __init__(self):
    try:
        trapworking = snmpEngine.transportDispatcher.jobsArePending()
    except:
        trapworking = -1

    if trapworking == 0:
        snmpEngine.transportDispatcher.jobStarted(1)

    elif trapworking == -1:
        print "starting"
        # UDP over IPv4, first listening interface/port
        config.addV1System(snmpEngine, 'my-area', 'public')

        # SecurityName <-> CommunityName mapping
        print "d0"
        config.addSocketTransport(
                                  snmpEngine,
                                  udp.domainName + (1,),
                                  udp.UdpTransport().openServerMode(( 'localhost', 162 ))
                                  )
        ntfrcv.NotificationReceiver(snmpEngine, cbFun)
        snmpEngine.transportDispatcher.jobStarted(1)
    else:
        print "Trap receiver already started."

def run(self):
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        print "fail"
        snmpEngine.transportDispatcher.closeDispatcher()
        raise

def cbFun(snmpEngine,
          stateReference,
          contextEngineId, contextName,
          varBinds,
          cbCtx):
    transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)
    print('Notification from %s, ContextEngineId "%s", ContextName "%s"' % (
        transportAddress, contextEngineId.prettyPrint(),
        contextName.prettyPrint()
        )
    )
    for obj in varBinds:
         print obj

trapStatus = threading.Thread(target = trapReceiverThread().run)
trapStatus.deamon = True

def start():
    global trapStatus
    if trapStatus.isAlive() == False:
        try:
            trapStatus.start();
        except:
            trapStatus = threading.Thread(target = trapReceiverThread().run)
            trapStatus.start();           

def stop():
    if snmpEngine.transportDispatcher.jobsArePending():
        print "stopping"
        """
        CODE to stop SocketTransport, transportDispatcher, and NotificationReceiver
        """
        snmpEngine.transportDispatcher.jobFinished(1)
        trapStatus.join()

def restart():
    stop()
    start()

1 个答案:

答案 0 :(得分:1)

由于陷阱被定义为局部变量transportDispater,因此可以通过完成作业#1并释放端口来停止该过程。

transportDispatcher.jobFinished(1)                
transportDispatcher.unregisterRecvCbFun(recvId=None)
transportDispatcher.unregisterTransport(udp.domainName)