PySNMP Project Logo

Project diary
Documentation
Examples
License
Download
Mailing lists

Projects using PySNMP
TwistedSNMP
Zenoss


Relevant projects
SNMPy
YAPSNMP
LibSMI
Scotty software

SourceForge Logo

import string
import socket
from pysnmp import session, ber

class snmptrapd (session.session):
    """Send SNMP trap to remote SNMP process
    """
    def __init__ (self, community):
        """Explicitly call superclass's constructor as it gets
           overloaded by this class constructor and pass a few
           arguments alone.
        """   
        session.session.__init__ (self, '127.0.0.1', community)

    def run (self, message):
        """Handle SNMP trap message received from remote SNMP agent. Return
           a tuple of enterprise Object ID, agent address, generic trap type,
           specific trap type, uptime and lists of Object IDs along with
           associated values.
        """   
        # Parse SNMP trap message
        (enterprise, addr, generic, specific, timeticks,\
         encoded_objids, encoded_values) = self.decode_trap (message)

        # Convert numeric enterprise Object ID into string representation
        enterprise = self.nums2str (enterprise)

        # Convert numeric Object IDs into string representation
        # and BER decode them
        objids = map (self.nums2str, map (self.decode_oid, encoded_objids))

        # BER decode the values of MIB variables (assuming they are strings!)
        values = map (self.decode_string, encoded_values)

        return (enterprise, addr, generic, specific, timeticks, \
                objids, values)

if __name__ == '__main__':
    """Run the module if it's invoked for execution
    """
    import sys

    usage = 'Usage: %s [[interface]:[port]] [communuty]' % sys.argv[0]
    iface = ''
    port = 162
    community = 'public'
    
    # Make sure we have got enough args
    if len (sys.argv) > 1 and sys.argv[1][0] == '-':
        print usage
        sys.exit (1)

    if len (sys.argv) > 1:
        tokens = string.split(sys.argv[1], ':')

        if len(tokens) == 2:
            iface = tokens[0]
            try:
                port = int(tokens[1])

            except ValueError:
                print 'Bad port number to listen on (should be integer): ' \
                      + str(tokens[1])
                print usage
                sys.exit(1)

        elif len(tokens) == 1:
            iface = tokens[0]
        else:
            print 'Bad interface:port value' + str(tokens)
            print usage
            sys.exit(1)
        
    if len(sys.argv) == 3:
        community = sys.argv[2]

    instance = snmptrapd (community)
        
    # Create trap server
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((iface, port))

    print 'Listening for SNMP traps on ' + str((iface, port))

    # Receive SNMP traps, process them, print details to stdout
    while 1:
        (message, peer) = sock.recvfrom(65536)

        if not message:
            sys.exit(0)
            
        # Process SNMP message
        (enterprise, addr, generic, \
         specific, timeticks, objids, values) = instance.run (message)

        # Report what is received
        print 'SNMP trap message from ' + str(peer)
        print 'Enterprise Object ID: ' + str(enterprise)
        print 'Agent address: ' + str(addr)
        print 'Generic trap type: ',
        for key in ber.TRAPS.keys():
            if ber.TRAPS[key] == generic:
                print key
                break
        else:
            print str(generic)
        print 'Specific trap type: ' + str(specific)
        print 'Agent uptime: ' + str(timeticks)

        if objids:
            print '\"Interesting\" information follows:'

            # Convert two lists into a list of tuples for easier printing
            results = map (None, objids, values)
            for (objid, value) in results:
                print objid + ' ---> ' + str(value)

Need help? Try PySNMP mailing lists.