Mixing pysnmp and stdin

Depending on the application, sometimes you want to have some socket operations going (such as loading a website) and have stdin being read. There are plenty of examples for this in python which usually boil down to making stdin behave like a socket and mixing it into the list of sockets select() cares about.

A while ago I asked an email list could I have pysnmp use a different socket map so I could add my own sockets in (UDP, TCP and a zmq to name a few) and the Ilya the author of pysnmp explained how pysnmp can use a foreign socket map.

This sample code below is merely an mixture of Ilya’s example code and the way stdin gets mixed into the fold.  I have also updated to the high-level pysnmp API which explains the slight differences in the calls.

from time import time
import sys
import asyncore
from pysnmp.hlapi import asyncore as snmpAC
from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher


class CmdlineClient(asyncore.file_dispatcher):
    def handle_read(self):
    buf = self.recv(1024)
    print "you said {}".format(buf)


def myCallback(snmpEngine, sendRequestHandle, errorIndication,
               errorStatus, errorIndex, varBinds, cbCtx):
    print "myCallback!!"
    if errorIndication:
        print(errorIndication)
        return
    if errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
              errorIndex and varBinds[int(errorIndex)-1] or '?')
             )
        return

    for oid, val in varBinds:
    if val is None:
        print(oid.prettyPrint())
    else:
        print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

sharedSocketMap = {}
transportDispatcher = AsynsockDispatcher()
transportDispatcher.setSocketMap(sharedSocketMap)
snmpEngine = snmpAC.SnmpEngine()
snmpEngine.registerTransportDispatcher(transportDispatcher)
sharedSocketMap[sys.stdin] = CmdlineClient(sys.stdin)

snmpAC.getCmd(
    snmpEngine,
    snmpAC.CommunityData('public'),
    snmpAC.UdpTransportTarget(('127.0.0.1', 161)),
    snmpAC.ContextData(),
    snmpAC.ObjectType(
        snmpAC.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)),
    cbFun=myCallback)

while True:
    asyncore.poll(timeout=0.5, map=sharedSocketMap)
    if transportDispatcher.jobsArePending() or transportDispatcher.transportsAreWorking():
        transportDispatcher.handleTimerTick(time())

Some interesting lines from the above code:

  • Lines 8-11 are the stdin class that is called (or rather its handle_read method is) when there is text available on stdin.
  • Line 34 is where pysnmp is told to use our socket map and not its inbuilt one
  • Line 37 is where we have used the socket map to say if we get input from stdin, what is the handler.
  • Lines 39-46 are sending a SNMP query using the high-level API
  • Lines 48-51 are my simple socket poller

With all this I can handle keyboard presses and network traffic, such as a simple SNMP poll.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *