четвъртък, 24 април 2014 г.

python SNMP v3 trap catcher

 Needs lots of work to be called finished but works this way too.


snmptrapcatcher.py

from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
import time
from datetime import datetime

datecheck=str(datetime.now().strftime("%d%m%y"))
logfile=str(datetime.now().strftime("SNMP-%d-%m-%y.log"))
tolog=open(logfile, 'a')
# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4
config.addSocketTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpTransport().openServerMode(('0.0.0.0', 161))
)

# SNMPv3/USM setup

# user: usr-md5-none, auth: MD5, priv NONE
config.addV3User(
    snmpEngine, 'snmpuser',
    config.usmHMACMD5AuthProtocol, 'snmppassword!'
)

# Callback function for receiving notifications
def cbFun(snmpEngine,
          stateReference,
          contextEngineId, contextName,
          varBinds,
          cbCtx):
    global datecheck
    global logfile
    global tolog
    if str(datetime.now().strftime("%d%m%y")) != datecheck:
            logfile=str(datetime.now().strftime("SNMP-%d-%m-%y.log"))
            tolog=open(logfile, 'a')
       tolog.write(datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    tolog.write('\n')
    #tolog.write('Notification received, ContextEngineId "%s", ContextName "%s"' % (
    #    contextEngineId.prettyPrint(), contextName.prettyPrint()
    #    )
    #)
    for name, val in varBinds:
        tolog.write('%s = %s\n' % (name.prettyPrint(), val.prettyPrint()))
    tolog.flush()


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

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

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

Няма коментари:

Публикуване на коментар