Python Forum

Full Version: Receiving snmp traps with more than one Community String
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the below snmp trap receiver. I have two community string, public and private.
I want to get traps from the devices who has com. string public and private.
In my db my com. strings are:
public
private

My code only get traps from private community strings.
How can i use it with more community strings?


#!/usr/bin/env python3.8

import asyncio
import concurrent.futures

from pysnmp.entity import engine, config
from pysnmp.carrier.asyncio.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
import json
from datetime import datetime

exec(open("/etc/epp/SNMP/mysqlconnector.py").read())

query= "SELECT community_string FROM nat_snmp_string WHERE status ='enable'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
com_str = cursor.fetchall()
for data in com_str:
   # print(data['community_string'])
    community = data['community_string']
    print(community)


class SnmpTrapDaemon():
#    @staticmethod
    def run_daemon(pool):
    
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        snmpEngine = engine.SnmpEngine()
    
        # Transport Setup
        config.addTransport(
            snmpEngine,
            udp.domainName,
            udp.UdpTransport().openServerMode(('192.168.1.200', '162'))
        )
    
        # SNMPv1/2c setup
        config.addV1System(
            snmpEngine, community, community)
    
        # Callback function for receiving notifications
        # noinspection PyUnusedLocal
        def cbFun(snmpEngine, stateReference, contextEngineId,
                contextName, varBinds, cbCtx):
    
            trap = {}
            for oid, val in varBinds:
                trap[oid.prettyPrint()] = val.prettyPrint()
            pool.submit(asyncio.run, process_trap(trap))
    
        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(snmpEngine, cbFun)
    
        snmpEngine.transportDispatcher.jobStarted(1)
        try:
            print('Trap Listener started on port 162. Press Ctrl-c to quit.')
            snmpEngine.transportDispatcher.runDispatcher()
        except KeyboardInterrupt:
            print('user quit')
        finally:
            snmpEngine.transportDispatcher.closeDispatcher()

async def process_trap(trap):
    print('Processing TRAP - this might take while...')
    await asyncio.sleep(3)
    for item in trap.items():
        print(item)
    print('...done')

def main():
    print('Starting SNMP-TRAP Processor')
    query= "SELECT community_string FROM nat_snmp_string WHERE status ='enable'"
    cursor = connection.cursor(dictionary=True)
    cursor.execute(query)
    com_str = cursor.fetchall()
    for data in com_str:
   # print(data['community_string'])
     community = data['community_string']
     print(community)


    pool = concurrent.futures.ThreadPoolExecutor(max_workers=50)
    SnmpTrapDaemon.run_daemon(pool)

if __name__ == '__main__':
    main()