pysnmp-apps-0.3.2/0000755000014400001440000000000011744502304014114 5ustar ilyausers00000000000000pysnmp-apps-0.3.2/PKG-INFO0000644000014400001440000000143011744502304015207 0ustar ilyausers00000000000000Metadata-Version: 1.0 Name: pysnmp-apps Version: 0.3.2 Summary: PySNMP applications Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: Telecommunications Industry Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: License :: OSI Approved :: BSD License pysnmp-apps-0.3.2/tools/0000755000014400001440000000000011744502304015254 5ustar ilyausers00000000000000pysnmp-apps-0.3.2/tools/pysnmpwalk0000755000014400001440000001126411732372270017417 0ustar ilyausers00000000000000#!/usr/bin/env python # # GETNEXT command generator # # Copyright 1999-2012 by Ilya Etingof . # import sys, time from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 from pysnmp import error def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s%s%s%s%s\ GETNEXT options:\n\ -C set various application specific behaviours:\n\ c: do not check returned OIDs are increasing\n\ t: display wall-clock time to complete the request\n\ p: print the number of variables found\n" % ( sys.argv[0], main.getUsage(), msgmod.getUsage(), secmod.getUsage(), mibview.getUsage(), target.getUsage(), pdu.getReadUsage() ) # Construct c/l interpreter for this app class Scanner( msgmod.MPScannerMixIn, secmod.SMScannerMixIn, mibview.MibViewScannerMixIn, target.TargetScannerMixIn, pdu.ReadPduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): def t_appopts(self, s): r' -C ' self.rv.append(base.ConfigToken('appopts')) class Parser( msgmod.MPParserMixIn, secmod.SMParserMixIn, mibview.MibViewParserMixIn, target.TargetParserMixIn, pdu.ReadPduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): def p_appOptions(self, args): ''' Option ::= ApplicationOption ApplicationOption ::= appopts whitespace string ApplicationOption ::= appopts string ''' class __Generator(base.GeneratorTemplate): def n_ApplicationOption(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: opt = node[2].attr else: opt = node[1].attr for c in opt: if c == 'c': ctx['ignoreNonIncreasingOids'] = 1 elif c == 't': ctx['displayWallClock'] = time.time() elif c == 'p': ctx['reportFoundVars'] = 1 else: raise error.PySnmpError('bad -C option - "%s"' % c) def generator(cbCtx, ast): snmpEngine, ctx = cbCtx return __Generator().preorder((snmpEngine, ctx), ast) snmpEngine = engine.SnmpEngine() try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generator((snmpEngine, ctx), ast) pdu.readPduGenerator((snmpEngine, ctx), ast) generator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) ctx['myHeadVars'] = [ rfc1902.ObjectName(x[0]) for x in ctx['varBinds'] ] # Run SNMP engine def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: if errorIndication != 'oidNotIncreasing' or \ not ctx.get('ignoreNonIncreasingOids'): sys.stderr.write('Error: %s\n' % errorIndication) return if errorStatus: sys.stderr.write( '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex)-1] or '?' ) ) return for varBindRow in varBindTable: colIdx = -1; inTableFlag = 0 for oid, val in varBindRow: colIdx = colIdx + 1 sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val )) if cbCtx['myHeadVars'][colIdx].isPrefixOf(oid): inTableFlag = 1 if cbCtx.get('reportFoundVars'): cbCtx['reportFoundVars'] = cbCtx['reportFoundVars'] + len(varBindRow) if not inTableFlag: return # stop on end-of-table return 1 # continue walking cmdgen.NextCommandGenerator().sendReq( snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx, ctx.get('contextEngineId'), ctx.get('contextName', '') ) try: snmpEngine.transportDispatcher.runDispatcher() except error.PySnmpError: sys.stderr.write('Error: %s\n' % sys.exc_info()[1]) sys.exit(-1) if ctx.get('reportFoundVars'): sys.stdout.write('Variables found: %s\n' % (ctx['reportFoundVars'] - 1)) if ctx.get('displayWallClock'): sys.stdout.write('Total traversal time = %.4f seconds\n' % (time.time() - ctx['displayWallClock'])) pysnmp-apps-0.3.2/tools/pysnmptrap0000755000014400001440000002032011742505430017415 0ustar ilyausers00000000000000#!/usr/bin/env python # # TRAP generator # # Copyright 1999-2012 by Ilya Etingof . # import sys, socket, time from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.proto.proxy import rfc2576 from pysnmp.proto import rfc1902 from pysnmp.proto.api import v1, v2c from pysnmp import error def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s%s%s\ TRAP options:\n\ -C: set various application specific behaviours:\n\ i: send INFORM-PDU, expect a response\n\ %s\ SNMPv1 TRAP management parameters:\n\ enterprise-oid agent generic-trap specific-trap uptime \n\ where:\n\ generic-trap: coldStart|warmStart|linkDown|linkUp|authenticationFailure|egpNeighborLoss|enterpriseSpecific\n\ SNMPv2/SNMPv3 management parameters:\n\ uptime trap-oid \n\ %s" % ( sys.argv[0], main.getUsage(), msgmod.getUsage(), secmod.getUsage(), mibview.getUsage(), target.getUsage(), pdu.getWriteUsage() ) # Construct c/l interpreter for this app class Scanner( msgmod.MPScannerMixIn, secmod.SMScannerMixIn, mibview.MibViewScannerMixIn, target.TargetScannerMixIn, pdu.ReadPduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): def t_appopts(self, s): r' -C ' self.rv.append(base.ConfigToken('appopts')) def t_genericTrap(self, s): r' coldStart|warmStart|linkDown|linkUp|authenticationFailure|egpNeighborLoss|enterpriseSpecific ' self.rv.append(base.ConfigToken('genericTrap', s)) class Parser( msgmod.MPParserMixIn, secmod.SMParserMixIn, mibview.MibViewParserMixIn, target.TargetParserMixIn, pdu.WritePduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): def p_trapParams(self, args): ''' TrapV1Params ::= EnterpriseOid whitespace AgentName whitespace GenericTrap whitespace SpecificTrap whitespace Uptime whitespace VarBinds EnterpriseOid ::= string AgentName ::= string GenericTrap ::= genericTrap SpecificTrap ::= string Uptime ::= string TrapV2cParams ::= Uptime whitespace TrapOid whitespace VarBinds TrapOid ::= string ''' def p_paramsSpec(self, args): ''' Params ::= TrapV1Params Params ::= TrapV2cParams ''' def p_appOptions(self, args): ''' Option ::= ApplicationOption ApplicationOption ::= appopts whitespace string ApplicationOption ::= appopts string ''' class __Generator(base.GeneratorTemplate): def n_ApplicationOption(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: opt = node[2].attr else: opt = node[1].attr for c in opt: if c == 'i': ctx['informMode'] = 1 else: raise error.PySnmpError('bad -C option - "%s"' % c) def n_EnterpriseOid(self, cbCtx, node): snmpEngine, ctx= cbCtx ctx['EnterpriseOid'] = node[0].attr def n_AgentName(self, cbCtx, node): snmpEngine, ctx = cbCtx try: ctx['AgentName'] = socket.gethostbyname(node[0].attr) except socket.error: raise error.PySnmpError( 'Bad agent name %s: %s' % (node[0].attr, sys.exc_info()[1]) ) def n_GenericTrap(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['GenericTrap'] = node[0].attr def n_SpecificTrap(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['SpecificTrap'] = node[0].attr def n_Uptime(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['Uptime'] = int(node[0].attr) def n_TrapV1Params_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx # Hack SNMP engine's uptime sysUpTime, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMPv2-MIB', 'sysUpTime' ) sysUpTime.syntax.createdAt = time.time() - float(ctx['Uptime'])/100 # Initialize v1 PDU with passed params, then proxy it into v2c PDU v1Pdu = v1.TrapPDU() v1.apiTrapPDU.setDefaults(v1Pdu) if 'EnterpriseOid' in ctx: v1.apiTrapPDU.setEnterprise(v1Pdu, ctx['EnterpriseOid']) if 'AgentName' in ctx: v1.apiTrapPDU.setAgentAddr(v1Pdu, ctx['AgentName']) if 'GenericTrap' in ctx: v1.apiTrapPDU.setGenericTrap(v1Pdu, ctx['GenericTrap']) if 'SpecificTrap' in ctx: v1.apiTrapPDU.setSpecificTrap(v1Pdu, ctx['SpecificTrap']) if 'Uptime' in ctx: v1.apiTrapPDU.setTimeStamp(v1Pdu, ctx['Uptime']) v2cPdu = rfc2576.v1ToV2(v1Pdu) # Drop first two var-binds of v2c PDU as they are set internally by # SNMP engine varBinds = v2c.apiPDU.getVarBinds(v2cPdu) if 'varBinds' not in ctx: ctx['varBinds'] = [] ctx['varBinds'] = varBinds[2:] + ctx['varBinds'] # Extract TrapOid from proxied PDU ctx['TrapOid' ] = varBinds[1][1].prettyPrint() def n_TrapOid(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['TrapOid'] = node[0].attr def n_TrapV2cParams_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx # Hack SNMP engine's uptime sysUpTime, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'sysUpTime') sysUpTime.syntax.createdAt = time.time() - float(ctx['Uptime'])/100 def generator(cbCtx, ast): snmpEngine, ctx = cbCtx return __Generator().preorder((snmpEngine, ctx), ast) snmpEngine = engine.SnmpEngine() try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generatorTrap((snmpEngine, ctx), ast) pdu.writePduGenerator((snmpEngine, ctx), ast) generator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) # Run SNMP engine def cbFun(sendRequestHandle, errorIndication, cbCtx): if errorIndication: sys.stderr.write('%s\n' % errorIndication) return snmpContext = context.SnmpContext(snmpEngine) # Agent-side VACM setup config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, ctx['securityName'], 'noAuthNoPriv', (), (), (1,3,6), contextName=ctx.get('contextName', '')) # v1 config.addVacmUser(snmpEngine, 2, ctx['securityName'], 'noAuthNoPriv', (), (), (1,3,6), contextName=ctx.get('contextName', '')) # v2c config.addVacmUser(snmpEngine, 3, ctx['securityName'], 'authPriv', (), (), (1,3,6), contextName=ctx.get('contextName', '')) # v3 config.addVacmUser(snmpEngine, 3, ctx['securityName'], 'authNoPriv', (), (), (1,3,6), contextName=ctx.get('contextName', '')) # v3 config.addVacmUser(snmpEngine, 3, ctx['securityName'], 'noAuthNoPriv', (), (), (1,3,6), contextName=ctx.get('contextName', '')) # v3 if 'contextName' in ctx: snmpContext.registerContextName( ctx.get('contextName', ''), # ref to base MIB instrum snmpEngine.msgAndPduDsp.mibInstrumController ) ctx['notificationName'] = 'myNotifyName' config.addNotificationTarget( snmpEngine, ctx['notificationName'], ctx['paramsName'], ctx['transportTag'], 'informMode' in ctx and 'inform' or 'trap' ) ntforg.NotificationOriginator(snmpContext).sendNotification( snmpEngine, ctx['notificationName'], ctx['TrapOid'], ctx['varBinds'], cbFun, ctx, ctx.get('contextName', '') ) try: snmpEngine.transportDispatcher.runDispatcher() except error.PySnmpError: sys.stderr.write('Error: %s\n' % sys.exc_info()[1]) sys.exit(-1) pysnmp-apps-0.3.2/tools/pysnmptranslate0000755000014400001440000001423311732372270020455 0ustar ilyausers00000000000000#!/usr/bin/env python # # Command-line MIB browser # # Copyright 1999-2012 by Ilya Etingof . # import sys from pyasn1.type import univ from pysnmp.entity import engine from pysnmp.proto import rfc3412 from pysnmp.smi import builder, instrum from pysnmp_apps.cli import main, pdu, mibview, base from pysnmp.smi.error import NoSuchObjectError from pysnmp import error from pyasn1.type import univ def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s\ TRANSLATE options:\n\ -T TRANSOPTS Set various options controlling report produced:\n\ d: print full details of the given OID\n\ a: dump the loaded MIB in a trivial form\n\ l: enable labeled OID report\n\ o: enable OID report\n\ s: enable dotted symbolic report\n\ %s\n" % ( sys.argv[0], main.getUsage(), mibview.getUsage(), pdu.getReadUsage() ) # Construct c/l interpreter for this app class Scanner( mibview.MibViewScannerMixIn, pdu.ReadPduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): def t_transopts(self, s): r' -T ' self.rv.append(base.ConfigToken('transopts')) class Parser( mibview.MibViewParserMixIn, pdu.ReadPduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): def p_transOptions(self, args): ''' Cmdline ::= Options whitespace Params Cmdline ::= Options Params Option ::= TranslateOption TranslateOption ::= transopts whitespace string TranslateOption ::= transopts string ''' class __Generator(base.GeneratorTemplate): def n_TranslateOption(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewProxy = ctx['mibViewProxy'] if len(node) > 2: opt = node[2].attr else: opt = node[1].attr for c in opt: mibViewProxy.translateMassMode = 1 if c == 'd': mibViewProxy.translateFullDetails = 1 mibViewProxy.translateMassMode = 0 elif c == 'a': mibViewProxy.translateTrivial = 1 elif c == 'l': mibViewProxy.translateLabeledOid = 1 elif c == 'o': mibViewProxy.translateNumericOid = 1 elif c == 's': mibViewProxy.translateSymbolicOid = 1 else: raise error.PySnmpError('unsupported sub-option \"%s\"' % c) def generator(cbCtx, ast): snmpEngine, ctx= cbCtx return __Generator().preorder((snmpEngine, ctx), ast) class MibViewProxy(mibview.MibViewProxy): # MIB translate options translateFullDetails = 0 translateTrivial = 0 translateLabeledOid = 0 translateNumericOid = 0 translateSymbolicOid = 0 # Implies SNMPWALK mode translateMassMode = 0 # Override base class defaults buildEqualSign = 0 _null = univ.Null() def getPrettyOidVal(self, mibViewController, oid, val): prefix, label, suffix = mibViewController.getNodeName(oid) modName, nodeDesc, _suffix = mibViewController.getNodeLocation(prefix) mibNode, = mibViewController.mibBuilder.importSymbols( modName, nodeDesc ) out = '' if self.translateFullDetails: if suffix: out = '%s::%s' % (modName, nodeDesc) out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ]) out = out + '\n' else: out = out + '%s::%s %s\n::= { %s }' % ( modName, nodeDesc, mibNode.asn1Print(), ' '.join( map(lambda x,y: '%s(%s)' % (y, x), prefix, label) ) ) elif self.translateTrivial: out = '%s ::= { %s %s' % ( len(label) > 1 and label[-2] or ".", label[-1], prefix[-1] ) if suffix: out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ]) out = out + ' }' elif self.translateLabeledOid: out = '.' + '.'.join( map(lambda x,y: '%s(%s)' % (y, x), prefix, label) ) if suffix: out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ]) elif self.translateNumericOid: out = '.' + '.'.join([ str(x) for x in prefix ]) if suffix: out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ]) elif self.translateSymbolicOid: out = '.' + '.'.join(label) if suffix: out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ]) if not out: out = mibview.MibViewProxy.getPrettyOidVal( self, mibViewController, oid, self._null ) return out mibInstrumController = instrum.MibInstrumController( builder.MibBuilder() ) # Load up MIB texts (DESCRIPTION, etc.) mibInstrumController.mibBuilder.loadTexts = 1 snmpEngine = engine.SnmpEngine( msgAndPduDsp=rfc3412.MsgAndPduDispatcher(mibInstrumController) ) try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) ctx['mibViewProxy'] = MibViewProxy(ctx['mibViewController']) mibview.generator((snmpEngine, ctx), ast) pdu.readPduGenerator((snmpEngine, ctx), ast) generator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) for oid, val in ctx['varBinds']: while 1: if val is None: val = univ.Null() sys.stdout.write('%s\n' % ctx['mibViewProxy'].getPrettyOidVal( ctx['mibViewController'], oid, val )) if not ctx['mibViewProxy'].translateMassMode: break try: oid, label, suffix = ctx['mibViewController'].getNextNodeName(oid) except NoSuchObjectError: break else: sys.stdout.write('\n') pysnmp-apps-0.3.2/tools/pysnmpset0000755000014400001440000000502311732372270017250 0ustar ilyausers00000000000000#!/usr/bin/env python # # SET command generator # # Copyright 1999-2012 by Ilya Etingof . # import sys from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine from pysnmp.entity.rfc3413 import cmdgen from pysnmp import error def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s%s%s%s%s" % ( sys.argv[0], main.getUsage(), msgmod.getUsage(), secmod.getUsage(), mibview.getUsage(), target.getUsage(), pdu.getWriteUsage() ) # Construct c/l interpreter for this app class Scanner( msgmod.MPScannerMixIn, secmod.SMScannerMixIn, mibview.MibViewScannerMixIn, target.TargetScannerMixIn, pdu.WritePduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): pass class Parser( msgmod.MPParserMixIn, secmod.SMParserMixIn, mibview.MibViewParserMixIn, target.TargetParserMixIn, pdu.WritePduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): pass snmpEngine = engine.SnmpEngine() try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generator((snmpEngine, ctx), ast) pdu.writePduGenerator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) # Run SNMP engine def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: sys.stderr.write('%s\n' % errorIndication) elif errorStatus: sys.stderr.write( '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) else: for oid, val in varBinds: sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val )) cmdgen.SetCommandGenerator().sendReq( snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx, ctx.get('contextEngineId'), ctx.get('contextName', '') ) try: snmpEngine.transportDispatcher.runDispatcher() except error.PySnmpError: sys.stderr.write('Error: %s\n' % sys.exc_info()[1]) sys.exit(-1) pysnmp-apps-0.3.2/tools/pysnmpget0000755000014400001440000000501711732372270017237 0ustar ilyausers00000000000000#!/usr/bin/env python # # GET command generator # # Copyright 1999-2012 by Ilya Etingof . # import sys from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine from pysnmp.entity.rfc3413 import cmdgen from pysnmp import error def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s%s%s%s%s" % ( sys.argv[0], main.getUsage(), msgmod.getUsage(), secmod.getUsage(), mibview.getUsage(), target.getUsage(), pdu.getReadUsage() ) # Construct c/l interpreter for this app class Scanner( msgmod.MPScannerMixIn, secmod.SMScannerMixIn, mibview.MibViewScannerMixIn, target.TargetScannerMixIn, pdu.ReadPduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): pass class Parser( msgmod.MPParserMixIn, secmod.SMParserMixIn, mibview.MibViewParserMixIn, target.TargetParserMixIn, pdu.ReadPduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): pass snmpEngine = engine.SnmpEngine() try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generator((snmpEngine, ctx), ast) pdu.readPduGenerator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) # Run SNMP engine def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: sys.stderr.write('%s\n' % errorIndication) elif errorStatus: sys.stderr.write( '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) else: for oid, val in varBinds: sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val )) cmdgen.GetCommandGenerator().sendReq( snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx, ctx.get('contextEngineId'), ctx.get('contextName', '') ) try: snmpEngine.transportDispatcher.runDispatcher() except error.PySnmpError: sys.stderr.write('Error: %s\n' % sys.exc_info()[1]) sys.exit(-1) pysnmp-apps-0.3.2/tools/pysnmpbulkwalk0000755000014400001440000001250711732372270020276 0ustar ilyausers00000000000000#!/usr/bin/env python # # GETBULK command generator # # Copyright 1999-2012 by Ilya Etingof . # import sys, time from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 from pysnmp import error def getUsage(): return "Usage: %s [OPTIONS] \n\ %s%s%s%s\ GETBULK options:\n\ -C BULKOPTS: set various application specific behaviours:\n\ n set non-repeaters to \n\ r set max-repetitions to \n\ c: do not check returned OIDs are increasing\n\ t: display wall-clock time to complete the request\n\ p: print the number of variables found\n\ %s%s" % ( sys.argv[0], main.getUsage(), msgmod.getUsage(), secmod.getUsage(), mibview.getUsage(), target.getUsage(), pdu.getReadUsage() ) # Construct c/l interpreter for this app class Scanner( msgmod.MPScannerMixIn, secmod.SMScannerMixIn, mibview.MibViewScannerMixIn, target.TargetScannerMixIn, pdu.ReadPduScannerMixIn, main.MainScannerMixIn, base.ScannerTemplate ): def t_appopts(self, s): r' -C ' self.rv.append(base.ConfigToken('appopts')) class Parser( msgmod.MPParserMixIn, secmod.SMParserMixIn, mibview.MibViewParserMixIn, target.TargetParserMixIn, pdu.ReadPduParserMixIn, main.MainParserMixIn, base.ParserTemplate ): def p_appOptions(self, args): ''' Option ::= ApplicationOption ApplicationOption ::= appopts whitespace string ApplicationOption ::= appopts string ''' class __Generator(base.GeneratorTemplate): def n_ApplicationOption(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: opt = node[2].attr else: opt = node[1].attr p = n = r = None for c in opt: if c == 'n': p = n = [] elif c == 'r': p = r = [] elif c == 'c': ctx['ignoreNonIncreasingOids'] = 1 p = None elif c == 't': ctx['displayWallClock'] = time.time() p = None elif c == 'p': ctx['reportFoundVars'] = 1 p = None elif p is not None and c >= '0' and c <= '9': p.append(c) else: raise error.PySnmpError('bad -C option - "%s"' % c) if n is not None: ctx['nonRepeaters'] = int(''.join(n)) if r is not None: ctx['maxRepetitions'] = int(''.join(r)) def generator(cbCtx, ast): snmpEngine, ctx = cbCtx return __Generator().preorder((snmpEngine, ctx), ast) snmpEngine = engine.SnmpEngine() try: # Parse c/l into AST ast = Parser().parse( Scanner().tokenize(' '.join(sys.argv[1:])) ) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generator((snmpEngine, ctx), ast) pdu.readPduGenerator((snmpEngine, ctx), ast) generator((snmpEngine, ctx), ast) except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) ctx['myHeadVars'] = [ rfc1902.ObjectName(x[0]) for x in ctx['varBinds'] ] # Run SNMP engine def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: if errorIndication != 'oidNotIncreasing' or \ not ctx.get('ignoreNonIncreasingOids'): sys.stderr.write('Error: %s\n' % errorIndication) return if errorStatus: sys.stderr.write( '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex)-1] or '?' ) ) return for varBindRow in varBindTable: colIdx = -1; inTableFlag = 0 for oid, val in varBindRow: colIdx = colIdx + 1 sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val )) if cbCtx['myHeadVars'][colIdx].isPrefixOf(oid): inTableFlag = 1 if cbCtx.get('reportFoundVars'): cbCtx['reportFoundVars'] = cbCtx['reportFoundVars'] + len(varBindRow) if not inTableFlag: return # stop on end-of-table return 1 # continue walking cmdgen.BulkCommandGenerator().sendReq( snmpEngine, ctx['addrName'], ctx.get('nonRepeaters', 0), ctx.get('maxRepetitions', 25), ctx['varBinds'], cbFun, ctx, ctx.get('contextEngineId'), ctx.get('contextName', '') ) try: snmpEngine.transportDispatcher.runDispatcher() except error.PySnmpError: sys.stderr.write('Error: %s\n' % sys.exc_info()[1]) sys.exit(-1) if ctx.get('reportFoundVars'): sys.stdout.write('Variables found: %s\n' % (ctx['reportFoundVars'] - 1)) if ctx.get('displayWallClock'): sys.stdout.write('Total traversal time = %.4f seconds\n' % (time.time() - ctx['displayWallClock'])) pysnmp-apps-0.3.2/MANIFEST.in0000644000014400001440000000020011415434153015643 0ustar ilyausers00000000000000include CHANGES LICENSE README recursive-include tools pysnmpget pysnmptranslate pysnmpwalk pysnmpbulkwalk pysnmpset pysnmptrap pysnmp-apps-0.3.2/pysnmp_apps.egg-info/0000755000014400001440000000000011744502304020157 5ustar ilyausers00000000000000pysnmp-apps-0.3.2/pysnmp_apps.egg-info/SOURCES.txt0000644000014400001440000000116611744502304022047 0ustar ilyausers00000000000000CHANGES LICENSE MANIFEST.in README setup.py pysnmp_apps/__init__.py pysnmp_apps/error.py pysnmp_apps.egg-info/PKG-INFO pysnmp_apps.egg-info/SOURCES.txt pysnmp_apps.egg-info/dependency_links.txt pysnmp_apps.egg-info/requires.txt pysnmp_apps.egg-info/top_level.txt pysnmp_apps.egg-info/zip-safe pysnmp_apps/cli/__init__.py pysnmp_apps/cli/base.py pysnmp_apps/cli/main.py pysnmp_apps/cli/mibview.py pysnmp_apps/cli/msgmod.py pysnmp_apps/cli/pdu.py pysnmp_apps/cli/secmod.py pysnmp_apps/cli/spark.py pysnmp_apps/cli/target.py tools/pysnmpbulkwalk tools/pysnmpget tools/pysnmpset tools/pysnmptranslate tools/pysnmptrap tools/pysnmpwalkpysnmp-apps-0.3.2/pysnmp_apps.egg-info/top_level.txt0000644000014400001440000000001411744502304022704 0ustar ilyausers00000000000000pysnmp_apps pysnmp-apps-0.3.2/pysnmp_apps.egg-info/requires.txt0000644000014400001440000000001511744502304022553 0ustar ilyausers00000000000000pysnmp>=4.2.2pysnmp-apps-0.3.2/pysnmp_apps.egg-info/PKG-INFO0000644000014400001440000000143011744502304021252 0ustar ilyausers00000000000000Metadata-Version: 1.0 Name: pysnmp-apps Version: 0.3.2 Summary: PySNMP applications Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: Telecommunications Industry Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: License :: OSI Approved :: BSD License pysnmp-apps-0.3.2/pysnmp_apps.egg-info/dependency_links.txt0000644000014400001440000000000111744502304024225 0ustar ilyausers00000000000000 pysnmp-apps-0.3.2/pysnmp_apps.egg-info/zip-safe0000644000014400001440000000000111502004013021571 0ustar ilyausers00000000000000 pysnmp-apps-0.3.2/CHANGES0000644000014400001440000000754011742505430015116 0ustar ilyausers00000000000000Revision 0.3.2 -------------- - MIB path mangiling reworked - Fix to make pysnmptrap INFORM C/L switch operational Revision 0.3.1 -------------- - Major overhawl for Python 2.4 -- 3.2 compatibility: + get rid of old-style types + drop string module usage + switch to rich comparation + drop explicit long integer type use + map()/filter() replaced with list comprehension + apply() replaced with */**args + switched to use 'key' sort() callback function + modified not to use py3k-incompatible exception syntax + dictionary operations made 2K/3K compatible Revision 0.2.11b ---------------- - Fix to ignore empty value in pysnmptranslate pretty printer Revision 0.2.11a ---------------- - New options (-Cp -Ct -Cc) implemented for pysnmp*walk tools. - All tools now report error OID. - EOM condition detection adjusted to reflect modified pysnmp API. - The pysnmptrap tool code cleaned up. - HEX values printout improved. Revision 0.2.10a ---------------- - Fix to SNMP Apps: pass contextEngineId and contextName from command line to SNMP App API. - The missing pysnmptrap tool added to distro and fixed to make it properly initializing SNMPv1/v2c trap PDU from command line parameters. Revision 0.2.9a --------------- - UDP over IPv6 transport added. - Fix to allow SET'ting values to MIB table instances. Revision 0.2.8a --------------- - API versioning mechanics retired (pysnmp_apps.v4 -> pysnmp_apps). - Attempt to use setuptools for package management whenever available. - The apps are now ready for py2exe processing. Revision 0.2.7a --------------- - Fixes to pysnmptranslate tool to output MIB text fields (DESCRIPTION etc.) Revision 0.2.6a --------------- - UNSTABLE ALPHA RELEASE. - Default timeout/retries set to net-snmp default values. - AES cipher now supported. Revision 0.2.5a --------------- - UNSTABLE ALPHA RELEASE. - The snmptranslate tool implemented. - The -d and -D debugging parameters implemented. - Minor fixes. Revision 0.2.4a --------------- - UNSTABLE ALPHA RELEASE. - pysnmp*walk tools modified to stop walking MIB on end-of-table rather than on end-of-mib to match net-snmp tools behaviour. - Bugfix to c/l params scanner -- allow other some printables other than alphas and numerics. - Handle syntax-less OID's whenever reported by broken Agents Revision 0.2.3a --------------- - UNSTABLE EARLY ALPHA RELEASE. - Adjusted to changed SMI model (in pysnmp 4.1.5a) - Minor fixes to Object Name command-line parser Revision 0.2.2a --------------- - UNSTABLE EARLY ALPHA RELEASE. - Adjusted to changed pysnmp.entity.config.addV3User() API - Fixes to command-line SNMPv3 protocols parser Revision 0.2.1a --------------- - UNSTABLE EARLY ALPHA RELEASE. - Re-worked to run on top of the latest pysnmp API (4.1.x) - CLI internals have been re-designed towards clearer modularity (see cli/base.py CVS log for details) - pysnmpset/pysnmpwalk/pysnmpbulkwalk tools added Revision 0.1.1a --------------- - UNSTABLE EARLY ALPHA RELEASE. - Fixed long-pending typo in usage formatting Revision 0.1.0a --------------- - UNSTABLE EARLY ALPHA RELEASE. - Re-worked to run on top of the latest pysnmp API (4.x) - SPARK-based parser used for c/l parsing - Rudimental API versioning implemented to let incompatible package branches to co-exist within the same Python installation. Revision 0.0.3 -------------- - Bugfix to scripts installation directive at setup.py. All apps now install as 'scripts'. - CLI classes adjucted to match new abstract ASN1 classes API Revision 0.0.2 -------------- - Bugfix to pysnmpwalk -- must always send Null value in request variable-bindings. Revision 0.0.1 -------------- - PySNMP-based applications split off the pysnmp package and re-released on their own - The command line interface to SNMP tools previously shipped along with PySNMP not reworked for a more consistent design and re-released within pysnmp-apps. pysnmp-apps-0.3.2/setup.py0000644000014400001440000000414211743343647015643 0ustar ilyausers00000000000000#!/usr/bin/env python import sys def howto_install_setuptools(): print("""Error: You need setuptools Python package! It's very easy to install it, just type (as root on Linux): wget http://peak.telecommunity.com/dist/ez_setup.py python ez_setup.py """) try: from setuptools import setup params = { 'install_requires': [ 'pysnmp>=4.2.2' ], 'zip_safe': True } except ImportError: for arg in sys.argv: if arg.find('egg') != -1: howto_install_setuptools() sys.exit(1) from distutils.core import setup params = {} if sys.version_info[:2] > (2, 4): params['requires'] = [ 'pysnmp(>=4.2.2)' ] params.update( { 'name': 'pysnmp-apps', 'version': '0.3.2', 'description': 'PySNMP applications', 'author': 'Ilya Etingof', 'author_email': 'ilya@glas.net', 'url': 'http://sourceforge.net/projects/pysnmp/', 'classifiers': [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'Intended Audience :: Telecommunications Industry', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Communications', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'License :: OSI Approved :: BSD License' ], 'license': 'BSD', 'packages': [ 'pysnmp_apps', 'pysnmp_apps.cli' ], 'scripts': [ 'tools/pysnmpget', 'tools/pysnmpset', 'tools/pysnmpwalk', 'tools/pysnmpbulkwalk', 'tools/pysnmptrap', 'tools/pysnmptranslate' ] } ) if "py2exe" in sys.argv: import py2exe # fix executables params['console'] = params['scripts'] del params['scripts'] # add files not found my modulefinder params['options'] = { 'py2exe': { 'includes': [ 'pysnmp.smi.mibs.*', 'pysnmp.smi.mibs.instances.*' ] } } setup(**params) pysnmp-apps-0.3.2/pysnmp_apps/0000755000014400001440000000000011744502304016465 5ustar ilyausers00000000000000pysnmp-apps-0.3.2/pysnmp_apps/__init__.py0000644000014400001440000000005610145406115020574 0ustar ilyausers00000000000000"""Various components of SNMP applications""" pysnmp-apps-0.3.2/pysnmp_apps/error.py0000644000014400001440000000016410145156462020175 0ustar ilyausers00000000000000"""Top-level exception classes """ from pysnmp import error class SnmpApplicationError(error.PySnmpError): pass pysnmp-apps-0.3.2/pysnmp_apps/cli/0000755000014400001440000000000011744502304017234 5ustar ilyausers00000000000000pysnmp-apps-0.3.2/pysnmp_apps/cli/target.py0000644000014400001440000001417411653214257021111 0ustar ilyausers00000000000000import socket from pysnmp_apps.cli import base from pysnmp.carrier.asynsock.dgram import udp, udp6 from pysnmp_apps.error import SnmpApplicationError from pysnmp.entity import config from pysnmp import error # Usage def getUsage(): return "\ Communication options\n\ -r RETRIES number of retries when sending request\n\ -t TIMEOUT request timeout (in seconds)\n\ Agent address:\n\ [:]\n\ transport-domain: \"udp\"|\"udp6\"\n\ transport-endpoint: \"IP\"|\"IPv6\"|\"FQDN\"[:\"port\"]\n\ " # Scanner class TargetScannerMixIn: def t_retries(self, s): r' -r ' self.rv.append(base.ConfigToken('retries')) def t_timeout(self, s): r' -t ' self.rv.append(base.ConfigToken('timeout')) def t_transport(self, s): r' (udp6)|(udp) ' self.rv.append(base.ConfigToken('transport', s)) # Parser class TargetParserMixIn: def p_targetSpec(self, args): ''' Option ::= CommOption CommOption ::= Retries Retries ::= retries string Retries ::= retries whitespace string CommOption ::= Timeout Timeout ::= timeout string Timeout ::= timeout whitespace string Agent ::= Transport semicolon Endpoint semicolon Format Agent ::= Transport semicolon Endpoint Agent ::= Endpoint semicolon Format Agent ::= Endpoint Transport ::= transport Endpoint ::= string Endpoint ::= lparen IPv6 rparen IPv6 ::= string IPv6 IPv6 ::= semicolon IPv6 IPv6 ::= Format ::= string ''' # Generator if hasattr(socket, 'has_ipv6') and socket.has_ipv6 and \ hasattr(socket, 'getaddrinfo'): _getaddrinfo = socket.getaddrinfo else: def _getaddrinfo(a, b, c, d): raise SnmpApplicationError('IPv6 not supported by the system') class __TargetGeneratorPassOne(base.GeneratorTemplate): defPort = '161' _snmpDomainMap = { 'udp': (udp.snmpUDPDomain, udp.UdpSocketTransport, lambda h,p: (socket.gethostbyname(h), int(p))), 'udp6': (udp6.snmpUDP6Domain, udp6.Udp6SocketTransport, lambda h,p: (_getaddrinfo(h,p,socket.AF_INET6, socket.SOCK_DGRAM)[0][4])) } _snmpDomainNameMap = { 2: 'udp', 10: 'udp6' } def n_Transport(self, cbCtx, node): snmpEngine, ctx = cbCtx if node[0].attr in self._snmpDomainMap: ( ctx['transportDomain'], ctx['transportModule'], ctx['addrRewriteFun'] ) = self._snmpDomainMap[node[0].attr] else: raise error.PySnmpError( 'Unsupported transport domain %s' % node[0].attr ) def n_Endpoint(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['transportAddress'] = node[0].attr def n_IPv6(self, cbCtx, node): snmpEngine, ctx = cbCtx if not len(node): if 'transportDomain' not in ctx: ( ctx['transportDomain'], ctx['transportModule'], ctx['addrRewriteFun'] ) = self._snmpDomainMap['udp6'] return if ctx.get('transportAddress') is None: ctx['transportAddress'] = '' if node[0] == 'semicolon': ctx['transportAddress'] = ctx['transportAddress'] + ':' else: ctx['transportAddress'] = ctx['transportAddress'] + node[0].attr def n_Format(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['transportFormat'] = node[0].attr def n_Agent_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'transportDomain' not in ctx: try: f = _getaddrinfo(ctx['transportAddress'], 0)[0][0] except: f = -1 ( ctx['transportDomain'], ctx['transportModule'], ctx['addrRewriteFun'] ) = self._snmpDomainMap[ self._snmpDomainNameMap.get(f, 'udp') ] if 'transportFormat' in ctx: ctx['transportAddress'] = ( ctx['transportAddress'], ctx['transportFormat'] ) del ctx['transportFormat'] else: ctx['transportAddress'] = ( ctx['transportAddress'], self.defPort) class __TargetGeneratorTrapPassOne(__TargetGeneratorPassOne): defPort = '162' class __TargetGeneratorPassTwo(base.GeneratorTemplate): def n_Retries(self, cbCtx, node): snmpEngine, ctx = cbCtx try: if len(node) > 2: ctx['retryCount'] = int(node[2].attr) else: ctx['retryCount'] = int(node[1].attr) except ValueError: raise error.PySnmpError('Bad retry value') def n_Timeout(self, cbCtx, node): snmpEngine, ctx = cbCtx try: if len(node) > 2: ctx['timeout'] = int(node[2].attr)*100 else: ctx['timeout'] = int(node[1].attr)*100 except: raise error.PySnmpError('Bad timeout value') def n_Agent_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['addrName'] = '%s-name' % ctx['paramsName'] ctx['transportTag'] = '%s-tag' % ctx['addrName'] config.addTargetAddr( snmpEngine, ctx['addrName'], ctx['transportDomain'], ctx['addrRewriteFun'](*ctx['transportAddress']), ctx['paramsName'], # net-snmp defaults ctx.get('timeout', 100), ctx.get('retryCount', 5), tagList=ctx['transportTag'] ) config.addSocketTransport( snmpEngine, ctx['transportDomain'], ctx['transportModule']().openClientMode() ) __TargetGeneratorTrapPassTwo = __TargetGeneratorPassTwo def generator(cbCtx, ast): snmpEngine, ctx = cbCtx __TargetGeneratorPassTwo().preorder( __TargetGeneratorPassOne().preorder((snmpEngine, ctx), ast), ast ) def generatorTrap(cbCtx, ast): snmpEngine, ctx = cbCtx __TargetGeneratorTrapPassTwo().preorder( __TargetGeneratorTrapPassOne().preorder((snmpEngine, ctx), ast), ast ) pysnmp-apps-0.3.2/pysnmp_apps/cli/base.py0000644000014400001440000000752211653212651020530 0ustar ilyausers00000000000000# Abstract interface to SNMP objects initializers import sys from pysnmp_apps.cli import spark # AST class ConfigToken: # Abstract grammar token def __init__(self, type, attr=None): self.type = type self.attr = attr def __eq__(self, other): return self.type == other def __ne__(self, other): return self.type != other def __lt__(self, other): return self.type < other def __le__(self, other): return self.type <= other def __gt__(self, other): return self.type > other def __ge__(self, other): return self.type >= other def __repr__(self): return self.attr or self.type def __str__(self): if self.attr is None: return '%s' % self.type else: return '%s(%s)' % (self.type, self.attr) class ConfigNode: # AST node class -- N-ary tree def __init__(self, type, attr=None): self.type, self.attr = type, attr self._kids = [] def __getitem__(self, i): return self._kids[i] def __len__(self): return len(self._kids) if sys.version_info[0] < 3: def __setslice__(self, low, high, seq): self._kids[low:high] = seq else: def __setitem__(self, idx, seq): self._kids[idx] = seq def __eq__(self, other): return self.type == other def __ne__(self, other): return self.type != other def __lt__(self, other): return self.type < other def __le__(self, other): return self.type <= other def __gt__(self, other): return self.type > other def __ge__(self, other): return self.type >= other def __str__(self): if self.attr is None: return self.type else: return '%s(%s)' % (self.type, self.attr) # Scanner class __ScannerTemplate(spark.GenericScanner): def tokenize(self, input): self.rv = [] spark.GenericScanner.tokenize(self, input) return self.rv class __FirstLevelScanner(__ScannerTemplate): def t_string(self, s): r' [!#\$%&\'\(\)\*\+,\.//0-9<=>\?@A-Z\\\^_`a-z\{\|\}~][!#\$%&\'\(\)\*\+,\-\.//0-9<=>\?@A-Z\\\^_`a-z\{\|\}~]* ' self.rv.append(ConfigToken('string', s)) class __SecondLevelScanner(__FirstLevelScanner): def t_semicolon(self, s): r' : ' self.rv.append(ConfigToken('semicolon')) def t_lparen(self, s): r' \[ ' self.rv.append(ConfigToken('lparen')) def t_rparen(self, s): r' \] ' self.rv.append(ConfigToken('rparen')) def t_quote(self, s): r' \" ' self.rv.append(ConfigToken('quote')) def t_whitespace(self, s): r' \s+ ' self.rv.append(ConfigToken('whitespace')) ScannerTemplate = __SecondLevelScanner # Parser class ParserTemplate(spark.GenericASTBuilder): initialSymbol = None def __init__(self, startSymbol=None): if startSymbol is None: startSymbol = self.initialSymbol spark.GenericASTBuilder.__init__(self, ConfigNode, startSymbol) def terminal(self, token): # Reduce to homogeneous AST. return ConfigNode(token.type, token.attr) # Generator class GeneratorTemplate(spark.GenericASTTraversal): def __init__(self): pass # Skip superclass constructor def typestring(self, node): return node.type def preorder(self, client, node): try: name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(client, node) else: self.default(client, node) except spark.GenericASTTraversalPruningException: return client for kid in node: self.preorder(client, kid) name = name + '_exit' if hasattr(self, name): func = getattr(self, name) func(client, node) return client def default(self, client, node): pass pysnmp-apps-0.3.2/pysnmp_apps/cli/msgmod.py0000644000014400001440000000236611653214041021100 0ustar ilyausers00000000000000from pysnmp_apps.cli import base from pysnmp import error # Usage def getUsage(): return "\ SNMP message processing options:\n\ -v VERSION SNMP version: \"1\"|\"2c\"|\"3\"\n\ " # Scanner class MPScannerMixIn: def t_version(self, s): r' -v ' self.rv.append(base.ConfigToken('version')) # Parser class MPParserMixIn: def p_mpSpec(self, args): ''' Option ::= SnmpVersionId SnmpVersionId ::= version string SnmpVersionId ::= version whitespace string ''' # Generator class __MPGenerator(base.GeneratorTemplate): _versionIdMap = { '1': 0, '2': 1, '2c': 1, '3': 3 } def n_SnmpVersionId(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: versionId = node[2].attr else: versionId = node[1].attr if versionId in self._versionIdMap: ctx['versionId'] = self._versionIdMap[versionId] else: raise error.PySnmpError('Bad version value %s' % versionId) def generator(cbCtx, ast): snmpEngine, ctx = cbCtx __MPGenerator().preorder((snmpEngine, ctx), ast) # Commit defaults if 'versionId' not in ctx: ctx['versionId'] = 3 pysnmp-apps-0.3.2/pysnmp_apps/cli/secmod.py0000644000014400001440000002032711653214006021062 0ustar ilyausers00000000000000from pysnmp_apps.cli import base from pysnmp.entity import config from pysnmp import error # Usage def getUsage(): return "\ SNMPv1/v2c security options:\n\ -c COMMUNITY community name\n\ SNMPv3 security options:\n\ -u SECURITY-NAME USM user security name\n\ -l SECURITY-LEVEL \"noAuthNoPriv\"|\"authNoPriv\"|\"authPriv\"\n\ -a AUTH-PROTOCOL \"MD5\"|\"SHA\"\n\ -A AUTH-KEY user authentication key\n\ -x PRIV-PROTOCOL \"DES\"|\"AES\"\n\ -X PRIV-KEY user privacy key\n\ -E CONTEXT-ENGINE-ID authoritative context engine ID\n\ -e ENGINE-ID authoritative SNMP engine ID (will discover)\n\ -n CONTEXT-NAME authoritative context name\n\ -Z ENGINE-BOOTS local SNMP engine uptime\n\ " # Scanner class SMScannerMixIn: # SNMPv1/v2 def t_community(self, s): r' -c ' self.rv.append(base.ConfigToken('community')) # SNMPv3 def t_authProtocol(self, s): r' -a ' self.rv.append(base.ConfigToken('authProtocol')) def t_authKey(self, s): r' -A ' self.rv.append(base.ConfigToken('authKey')) def t_privProtocol(self, s): r' -x ' self.rv.append(base.ConfigToken('privProtocol')) def t_privKey(self, s): r' -X ' self.rv.append(base.ConfigToken('privKey')) def t_securityName(self, s): r' -u ' self.rv.append(base.ConfigToken('securityName')) def t_securityLevel(self, s): r' -l ' self.rv.append(base.ConfigToken('securityLevel')) def t_engineID(self, s): r' -e ' self.rv.append(base.ConfigToken('engineID')) def t_contextEngineId(self, s): r' -E ' self.rv.append(base.ConfigToken('contextEngineId')) def t_contextName(self, s): r' -n ' self.rv.append(base.ConfigToken('contextName')) def t_engineBoots(self, s): r' -Z ' self.rv.append(base.ConfigToken('engineBoots')) # Parser class SMParserMixIn: def p_smSpec(self, args): ''' Option ::= SnmpV1Option Option ::= SnmpV3Option SnmpV1Option ::= Community Community ::= community string Community ::= community whitespace string SnmpV3Option ::= AuthProtocol SnmpV3Option ::= AuthKey SnmpV3Option ::= PrivProtocol SnmpV3Option ::= PrivKey SnmpV3Option ::= SecurityName SnmpV3Option ::= SecurityLevel SnmpV3Option ::= EngineID SnmpV3Option ::= ContextEngineId SnmpV3Option ::= ContextName SnmpV3Option ::= EngineBoots AuthProtocol ::= authProtocol string AuthProtocol ::= authProtocol whitespace string AuthKey ::= authKey string AuthKey ::= authKey whitespace string PrivProtocol ::= privProtocol string PrivProtocol ::= privProtocol whitespace string PrivKey ::= privKey string PrivKey ::= privKey whitespace string SecurityName ::= securityName string SecurityName ::= securityName whitespace string SecurityLevel ::= securityLevel string SecurityLevel ::= securityLevel whitespace string EngineID ::= engineID string EngineID ::= engineID whitespace string ContextEngineId ::= contextEngineId string ContextEngineId ::= contextEngineId whitespace string ContextName ::= contextName string ContextName ::= contextName whitespace string EngineBoots ::= engineBoots string EngineBoots ::= engineBoots whitespace string ''' # Generator class __SMGenerator(base.GeneratorTemplate): # SNMPv1/v2 def n_Community(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['communityName'] = node[2].attr else: ctx['communityName'] = node[1].attr # SNMPv3 def n_AuthProtocol(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: p = node[2].attr.upper() else: p = node[1].attr.upper() if p.find('MD5') != -1: ctx['authProtocol'] = config.usmHMACMD5AuthProtocol elif p.find('SHA') != -1: ctx['authProtocol'] = config.usmHMACSHAAuthProtocol else: raise error.PySnmpError('Unknown auth protocol \"%s\"' % p) def n_AuthKey(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['authKey'] = node[2].attr else: ctx['authKey'] = node[1].attr def n_PrivProtocol(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: p = node[2].attr.upper() else: p = node[1].attr.upper() if p.find('DES') != -1: ctx['privProtocol'] = config.usmDESPrivProtocol elif p.find('AES') != -1: ctx['privProtocol'] = config.usmAesCfb128Protocol else: raise error.PySnmpError('Unknown priv protocol \"%s\"' % p) def n_PrivKey(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['privKey'] = node[2].attr else: ctx['privKey'] = node[1].attr def n_SecurityName(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['securityName'] = node[2].attr else: ctx['securityName'] = node[1].attr def n_SecurityLevel(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['securityLevel'] = node[2].attr else: ctx['securityLevel'] = node[1].attr def n_EngineID(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['engineID'] = node[2].attr else: ctx['engineID'] = node[1].attr def n_ContextEngineId(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['contextEngineId'] = node[2].attr else: ctx['contextEngineId'] = node[1].attr def n_ContextName(self, cbCtx, node): snmpEngine, ctx = cbCtx if len(node) > 2: ctx['contextName'] = node[2].attr else: ctx['contextName'] = node[1].attr def n_EngineBoots(self, cbCtx, node): # XXX snmpEngine, ctx = cbCtx if len(node) > 2: ctx['engineBoots'] = node[2].attr else: ctx['engineBoots'] = node[1].attr def generator(cbCtx, ast): snmpEngine, ctx = cbCtx __SMGenerator().preorder(cbCtx, ast) # Commit collected data if ctx['versionId'] == 3: if 'securityName' not in ctx: raise error.PySnmpError('Security name not specified') if 'securityLevel' not in ctx: raise error.PySnmpError('Security level not specified') if ctx['securityLevel'] == 'noAuthNoPriv': if 'authKey' in ctx: del ctx['authKey'] if 'privKey' in ctx: del ctx['privKey'] elif ctx['securityLevel'] == 'authNoPriv': if 'privKey' in ctx: del ctx['privKey'] if 'authKey' in ctx: if 'authProtocol' not in ctx: ctx['authProtocol'] = config.usmHMACMD5AuthProtocol else: ctx['authProtocol'] = config.usmNoAuthProtocol ctx['authKey'] = None if 'privKey' in ctx: if 'privProtocol' not in ctx: ctx['privProtocol'] = config.usmDESPrivProtocol else: ctx['privProtocol'] = config.usmNoPrivProtocol ctx['privKey'] = None config.addV3User( snmpEngine, ctx['securityName'], ctx['authProtocol'], ctx['authKey'], ctx['privProtocol'], ctx['privKey'] ) else: # SNMPv1/v2c if 'communityName' not in ctx: raise error.PySnmpError('Community name not specified') ctx['securityName'] = 'my-agent' ctx['securityLevel'] = 'noAuthNoPriv' config.addV1System( snmpEngine, ctx['securityName'], ctx['communityName'] ) ctx['paramsName'] = '%s-params' % ctx['securityName'] config.addTargetParams( snmpEngine, ctx['paramsName'],ctx['securityName'], ctx['securityLevel'], ctx['versionId'] ) pysnmp-apps-0.3.2/pysnmp_apps/cli/mibview.py0000644000014400001440000003000011732372270021245 0ustar ilyausers00000000000000# C/L interface to MIB variables. Mimics Net-SNMP CLI. import os from pyasn1.type import univ from pysnmp_apps.cli import base from pysnmp.proto import rfc1902 from pysnmp.smi import builder from pysnmp import error # Usage def getUsage(): return "\ MIB options:\n\ -m MIB[:...] load given list of MIBs (ALL loads everything)\n\ -M DIR[:...] look in given list of directories for MIBs\n\ -O OUTOPTS Toggle various defaults controlling output display:\n\ q: removes the equal sign and type information\n\ Q: removes the type information\n\ f: print full OIDs on output\n\ s: print only last symbolic element of OID\n\ S: print MIB module-id plus last element\n\ u: print OIDs using UCD-style prefix suppression\n\ n: print OIDs numerically\n\ e: print enums numerically\n\ b: do not break OID indexes down\n\ E: include a \" to escape the quotes in indices\n\ X: place square brackets around each index\n\ T: print value in hex\n\ v: print values only (not OID = value)\n\ U: don't print units\n\ t: output timeticks values as raw numbers\n\ -I INOPTS Toggle various defaults controlling input parsing:\n\ h: don't apply DISPLAY-HINTs\n\ u: top-level OIDs must have '.' prefix (UCD-style)\n\ " # Scanner class MibViewScannerMixIn: def t_mibfiles(self, s): r' -m ' self.rv.append(base.ConfigToken('mibfiles')) def t_mibdirs(self, s): r' -M ' self.rv.append(base.ConfigToken('mibdirs')) def t_outputopts(self, s): r' -O ' self.rv.append(base.ConfigToken('outputopts')) def t_inputopts(self, s): r' -I ' self.rv.append(base.ConfigToken('inputopts')) # Parser class MibViewParserMixIn: def p_mibView(self, args): ''' Option ::= GeneralOption Option ::= OutputOption Option ::= InputOption GeneralOption ::= MibDirList MibDirList ::= mibdirs MibDirs MibDirList ::= mibdirs whitespace MibDirs MibDirs ::= MibDir semicolon MibDirs MibDirs ::= MibDir MibDir ::= string GeneralOption ::= MibFileList MibFileList ::= mibfiles MibFiles MibFileList ::= mibfiles whitespace MibFiles MibFiles ::= MibFile semicolon MibFiles MibFiles ::= MibFile MibFile ::= string OutputOption ::= outputopts string OutputOption ::= outputopts whitespace string InputOption ::= inputopts string InputOption ::= inputopts whitespace string ''' # Generator class __MibViewGenerator(base.GeneratorTemplate): # Load MIB modules def n_MibFile(self, cbCtx, node): snmpEngine, ctx = cbCtx mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder if node[0].attr.lower() == 'all': mibBuilder.loadModules() else: mibBuilder.loadModules(node[0].attr) def n_MibDir(self, cbCtx, node): snmpEngine, ctx = cbCtx mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibBuilder.setMibSources( *mibBuilder.getMibSources() + (builder.ZipMibSource(node[0].attr).init(),) ) def n_OutputOption(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewProxy = ctx['mibViewProxy'] if len(node) > 2: opt = node[2].attr else: opt = node[1].attr for c in opt: if c == 'q': mibViewProxy.buildEqualSign = 0 mibViewProxy.buildTypeInfo = 0 elif c == 'Q': mibViewProxy.buildTypeInfo = 0 elif c == 'f': mibViewProxy.buildModInfo = 0 mibViewProxy.buildObjectDesc = 0 mibViewProxy.buildAbsoluteName = 1 elif c == 's': mibViewProxy.buildModInfo = 0 mibViewProxy.buildObjectDesc = 1 elif c == 'S': mibViewProxy.buildObjectDesc = 1 elif c == 'u': pass elif c == 'n': mibViewProxy.buildObjectDesc = 0 mibViewProxy.buildModInfo = 0 mibViewProxy.buildNumericName = 1 mibViewProxy.buildNumericIndices = 1 mibViewProxy.buildAbsoluteName = 1 elif c == 'e': raise error.PySnmpError('Option not implemented') elif c == 'b': mibViewProxy.buildNumericIndices = 1 elif c == 'E': mibViewProxy.buildEscQuotes = 1 elif c == 'X': mibViewProxy.buildSquareBrackets = 1 elif c == 'T': mibViewProxy.buildHexVals = 1 elif c == 'v': mibViewProxy.buildValueOnly = 1 elif c == 'U': mibViewProxy.buildUnits = 0 elif c == 't': mibViewProxy.buildRawTimeTicks = 1 pass elif c == 'R': mibViewProxy.buildRawVals = 1 else: raise error.PySnmpError( 'Unknown output option %s at %s' % (c, self) ) def n_InputOption(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewProxy = ctx['mibViewProxy'] if len(node) > 2: opt = node[2].attr else: opt = node[1].attr for c in opt: if c == 'R': pass elif c == 'b': pass elif c == 'u': mibViewProxy.defaultOidPrefix = ( 'iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2' ) elif c == 'r': pass elif c == 'h': pass else: raise error.PySnmpError( 'Unknown input option %s at %s' % (c, self) ) def generator(cbCtx, ast): snmpEngine, ctx = cbCtx if 'mibViewProxy' not in ctx: ctx['mibViewProxy'] = MibViewProxy(ctx['mibViewController']) return __MibViewGenerator().preorder((snmpEngine, ctx), ast) class UnknownSyntax: def prettyOut(self, val): return str(val) unknownSyntax = UnknownSyntax() # Proxy MIB view class MibViewProxy: # Defaults defaultOidPrefix = ( 'iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system' ) defaultMibs = ('SNMPv2-MIB',) defaultMibDirs = () # MIB parsing options # currently N/A # MIB output options buildModInfo = 1 buildObjectDesc = 1 buildNumericName = 0 buildAbsoluteName = 0 buildNumericIndices = 0 buildEqualSign = 1 buildTypeInfo = 1 buildEscQuotes = 0 buildSquareBrackets = 0 buildHexVals = 0 buildRawVals = 0 buildRawTimeTicks = 0 buildGuessedStringVals = 1 buildValueOnly = 0 buildUnits = 1 # MIB input options parseAsRandomAccessMib = 1 parseAsRegExp = 0 parseAsRelativeOid = 1 parseAndCheckIndices = 1 parseAsDisplayHint = 1 def __init__(self, mibViewController): if 'PYSNMPOIDPREFIX' in os.environ: self.defaultOidPrefix = os.environ['PYSNMPOIDPREFIX'] if 'PYSNMPMIBS' in os.environ: self.defaultMibs = os.environ['PYSNMPMIBS'].split(':') if 'PYSNMPMIBDIRS' in os.environ: self.defaultMibDirs = os.environ['PYSNMPMIBDIRS'].split(':') if self.defaultMibDirs: mibViewController.mibBuilder.setMibSources( *mibViewController.mibBuilder.getMibSources() + tuple( [ builder.ZipMibSource(m).init() for m in self.defaultMibDirs ] ) ) if self.defaultMibs: mibViewController.mibBuilder.loadModules(*self.defaultMibs) self.__oidValue = univ.ObjectIdentifier() self.__intValue = univ.Integer() self.__timeValue = rfc1902.TimeTicks() def getPrettyOidVal(self, mibViewController, oid, val): prefix, label, suffix = mibViewController.getNodeName(oid) modName, nodeDesc, _suffix = mibViewController.getNodeLocation(prefix) out = '' # object name if not self.buildValueOnly: if self.buildModInfo: out = '%s::' % modName if self.buildObjectDesc: out = out + nodeDesc else: if self.buildNumericName: name = prefix else: name = label if not self.buildAbsoluteName: name = name[len(self.defaultOidPrefix):] out = out + '.'.join([ str(x) for x in name ]) if suffix: if suffix == (0,): out = out + '.0' else: m, n, s = mibViewController.getNodeLocation(prefix[:-1]) rowNode, = mibViewController.mibBuilder.importSymbols( m, n ) if self.buildNumericIndices: out = out + '.' + '.'.join([ str(x) for x in suffix ]) else: try: for i in rowNode.getIndicesFromInstId(suffix): if self.buildEscQuotes: out = out + '.\\\"%s\\\"' % i.prettyOut(i) elif self.buildSquareBrackets: out = out + '.[%s]' % i.prettyOut(i) else: out = out + '.\"%s\"' % i.prettyOut(i) except AttributeError: out = out + '.' + '.'.join( [ str(x) for x in suffix ] ) if self.buildEqualSign: out = out + ' = ' else: out = out + ' ' # Value if isinstance(val, univ.Null): return out + val.prettyPrint() mibNode, = mibViewController.mibBuilder.importSymbols( modName, nodeDesc ) if hasattr(mibNode, 'syntax'): syntax = mibNode.syntax else: syntax = val if syntax is None: # lame Agent may return a non-instance OID syntax = unknownSyntax if self.buildTypeInfo: out = out + '%s: ' % syntax.__class__.__name__ if self.buildRawVals: out = out + str(val) elif self.buildHexVals: # XXX make it always in hex? if self.__intValue.isSuperTypeOf(val): out = out + '%x' % int(val) elif self.__oidValue.isSuperTypeOf(val): out = out + ' '.join([ '%x' % x for x in tuple(val) ]) else: out = out + ' '.join([ '%.2x' % ord(x) for x in str(val) ]) elif self.__timeValue.isSameTypeWith(val): if self.buildRawTimeTicks: out = out + str(int(val)) else: # TimeTicks is not a TC val = int(val) d, m = divmod(val, 8640000) out = out + '%d days ' % d d, m = divmod(m, 360000) out = out + '%d:' % d d, m = divmod(m, 6000) out = out + '%d:' % d d, m = divmod(m, 100) out = out + '%d.%d' % (d, m) elif self.__oidValue.isSuperTypeOf(val): oid, label, suffix = mibViewController.getNodeName(val) out = out + '.'.join( label + tuple([ str(x) for x in suffix ]) ) else: out = out + syntax.prettyOut(val) if self.buildUnits: if hasattr(mibNode, 'getUnits'): out = out + ' %s' % mibNode.getUnits() return out def setPrettyOidValue(self, oid, val, t): return oid, val pysnmp-apps-0.3.2/pysnmp_apps/cli/spark.py0000644000014400001440000003372011653212713020734 0ustar ilyausers00000000000000# Copyright (c) 1998-2000 John Aycock # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __version__ = 'SPARK-0.6.1' import re import sys def _namelist(instance): namelist, namedict, classlist = [], {}, [instance.__class__] for c in classlist: for b in c.__bases__: classlist.append(b) # for name in dir(c): for name in c.__dict__.keys(): if name not in namedict: namelist.append(name) namedict[name] = 1 return namelist class GenericScanner: def __init__(self): pattern = self.reflect() self.re = re.compile(pattern, re.VERBOSE) self.index2func = {} for name, number in self.re.groupindex.items(): self.index2func[number-1] = getattr(self, 't_' + name) def makeRE(self, name): doc = getattr(self, name).__doc__ rv = '(?P<%s>%s)' % (name[2:], doc) return rv def reflect(self): rv = [] for name in _namelist(self): if name[:2] == 't_' and name != 't_default': rv.append(self.makeRE(name)) rv.append(self.makeRE('t_default')) return '|'.join(rv) def error(self, s, pos): sys.stderr.write("Lexical error at position %s" % pos) raise SystemExit def tokenize(self, s): pos = 0 n = len(s) while pos < n: m = self.re.match(s, pos) if m is None: self.error(s, pos) groups = m.groups() for i in range(len(groups)): if groups[i] and i in self.index2func: self.index2func[i](groups[i]) pos = m.end() def t_default(self, s): r'( . | \n )+' pass class GenericParser: def __init__(self, start): self.rules = {} self.rule2func = {} self.rule2name = {} self.collectRules() self.startRule = self.augment(start) self.ruleschanged = 1 _START = 'START' _EOF = 'EOF' # # A hook for GenericASTBuilder and GenericASTMatcher. # def preprocess(self, rule, func): return rule, func def addRule(self, doc, func): rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': index.append(i-1) index.append(len(rules)) for i in range(len(index)-1): lhs = rules[index[i]] rhs = rules[index[i]+2:index[i+1]] rule = (lhs, tuple(rhs)) rule, fn = self.preprocess(rule, func) if lhs in self.rules: self.rules[lhs].append(rule) else: self.rules[lhs] = [ rule ] self.rule2func[rule] = fn self.rule2name[rule] = func.__name__[2:] self.ruleschanged = 1 def collectRules(self): for name in _namelist(self): if name[:2] == 'p_': func = getattr(self, name) doc = func.__doc__ self.addRule(doc, func) def augment(self, start): # # Tempting though it is, this isn't made into a call # to self.addRule() because the start rule shouldn't # be subject to preprocessing. # startRule = (self._START, ( start, self._EOF )) self.rule2func[startRule] = lambda args: args[0] self.rules[self._START] = [ startRule ] self.rule2name[startRule] = '' return startRule def makeFIRST(self): union = {} self.first = {} for rulelist in self.rules.values(): for lhs, rhs in rulelist: if lhs not in self.first: self.first[lhs] = {} if len(rhs) == 0: self.first[lhs][None] = 1 continue sym = rhs[0] if sym not in self.rules: self.first[lhs][sym] = 1 else: union[(sym, lhs)] = 1 changes = 1 while changes: changes = 0 for src, dest in union.keys(): destlen = len(self.first[dest]) self.first[dest].update(self.first[src]) if len(self.first[dest]) != destlen: changes = 1 # # An Earley parser, as per J. Earley, "An Efficient Context-Free # Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley, # "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis, # Carnegie-Mellon University, August 1968, p. 27. # def typestring(self, token): return None def error(self, token): sys.stderr.write("Syntax error at or near `%s' token" % token) raise SystemExit def parse(self, tokens): tree = {} tokens.append(self._EOF) states = { 0: [ (self.startRule, 0, 0) ] } if self.ruleschanged: self.makeFIRST() for i in range(len(tokens)): states[i+1] = [] if states[i] == []: break self.buildState(tokens[i], states, i, tree) # _dump(tokens, states) if i < len(tokens)-1 or states[i+1] != [(self.startRule, 2, 0)]: # --ilya # del tokens[-1] self.error(tokens[i-1]) rv = self.buildTree(tokens, tree, ((self.startRule, 2, 0), i+1)) del tokens[-1] return rv def buildState(self, token, states, i, tree): needsCompletion = {} state = states[i] predicted = {} for item in state: rule, pos, parent = item lhs, rhs = rule # # A -> a . (completer) # if pos == len(rhs): if len(rhs) == 0: needsCompletion[lhs] = (item, i) for pitem in states[parent]: if pitem is item: break prule, ppos, pparent = pitem plhs, prhs = prule if prhs[ppos:ppos+1] == (lhs,): new = (prule, ppos+1, pparent) if new not in state: state.append(new) tree[(new, i)] = [(item, i)] else: tree[(new, i)].append((item, i)) continue nextSym = rhs[pos] # # A -> a . B (predictor) # if nextSym in self.rules: # # Work on completer step some more; for rules # with empty RHS, the "parent state" is the # current state we're adding Earley items to, # so the Earley items the completer step needs # may not all be present when it runs. # if nextSym in needsCompletion: new = (rule, pos+1, parent) olditem_i = needsCompletion[nextSym] if new not in state: state.append(new) tree[(new, i)] = [olditem_i] else: tree[(new, i)].append(olditem_i) # # Has this been predicted already? # if nextSym in predicted: continue predicted[nextSym] = 1 ttype = token is not self._EOF and \ self.typestring(token) or \ None if ttype is not None: # # Even smarter predictor, when the # token's type is known. The code is # grungy, but runs pretty fast. Three # cases are looked for: rules with # empty RHS; first symbol on RHS is a # terminal; first symbol on RHS is a # nonterminal (and isn't nullable). # for prule in self.rules[nextSym]: new = (prule, 0, i) prhs = prule[1] if len(prhs) == 0: state.append(new) continue prhs0 = prhs[0] if prhs0 not in self.rules: if prhs0 != ttype: continue else: state.append(new) continue first = self.first[prhs0] if None not in first and \ ttype not in first: continue state.append(new) continue for prule in self.rules[nextSym]: # # Smarter predictor, as per Grune & # Jacobs' _Parsing Techniques_. Not # as good as FIRST sets though. # prhs = prule[1] if len(prhs) > 0 and \ prhs[0] not in self.rules and \ token != prhs[0]: continue state.append((prule, 0, i)) # # A -> a . c (scanner) # elif token == nextSym: #assert new not in states[i+1] states[i+1].append((rule, pos+1, parent)) def buildTree(self, tokens, tree, root): stack = [] self.buildTree_r(stack, tokens, -1, tree, root) return stack[0] def buildTree_r(self, stack, tokens, tokpos, tree, root): (rule, pos, parent), state = root while pos > 0: want = ((rule, pos, parent), state) if want not in tree: # # Since pos > 0, it didn't come from closure, # and if it isn't in tree[], then there must # be a terminal symbol to the left of the dot. # (It must be from a "scanner" step.) # pos = pos - 1 state = state - 1 stack.insert(0, tokens[tokpos]) tokpos = tokpos - 1 else: # # There's a NT to the left of the dot. # Follow the tree pointer recursively (>1 # tree pointers from it indicates ambiguity). # Since the item must have come about from a # "completer" step, the state where the item # came from must be the parent state of the # item the tree pointer points to. # children = tree[want] if len(children) > 1: child = self.ambiguity(children) else: child = children[0] tokpos = self.buildTree_r(stack, tokens, tokpos, tree, child) pos = pos - 1 (crule, cpos, cparent), cstate = child state = cparent lhs, rhs = rule result = self.rule2func[rule](stack[:len(rhs)]) stack[:len(rhs)] = [result] return tokpos def ambiguity(self, children): # # XXX - problem here and in collectRules() if the same # rule appears in >1 method. But in that case the # user probably gets what they deserve :-) Also # undefined results if rules causing the ambiguity # appear in the same method. # sortlist = [] name2index = {} for i in range(len(children)): ((rule, pos, parent), index) = children[i] lhs, rhs = rule name = self.rule2name[rule] sortlist.append((len(rhs), name)) name2index[name] = i sortlist.sort() l = [ x[1] for x in sortlist ] return children[name2index[self.resolve(l)]] def resolve(self, list): # # Resolve ambiguity in favor of the shortest RHS. # Since we walk the tree from the top down, this # should effectively resolve in favor of a "shift". # return list[0] # # GenericASTBuilder automagically constructs a concrete/abstract syntax tree # for a given input. The extra argument is a class (not an instance!) # which supports the "__setslice__" and "__len__" methods. # # XXX - silently overrides any user code in methods. # class GenericASTBuilder(GenericParser): def __init__(self, AST, start): GenericParser.__init__(self, start) self.AST = AST def preprocess(self, rule, func): rebind = lambda lhs, self=self: \ lambda args, lhs=lhs, self=self: \ self.buildASTNode(args, lhs) lhs, rhs = rule return rule, rebind(lhs) def buildASTNode(self, args, lhs): children = [] for arg in args: if isinstance(arg, self.AST): children.append(arg) else: children.append(self.terminal(arg)) return self.nonterminal(lhs, children) def terminal(self, token): return token def nonterminal(self, type, args): rv = self.AST(type) rv[:len(args)] = args return rv # # GenericASTTraversal is a Visitor pattern according to Design Patterns. For # each node it attempts to invoke the method n_, falling # back onto the default() method if the n_* can't be found. The preorder # traversal also looks for an exit hook named n__exit (no default # routine is called if it's not found). To prematurely halt traversal # of a subtree, call the prune() method -- this only makes sense for a # preorder traversal. Node type is determined via the typestring() method. # class GenericASTTraversalPruningException(Exception): pass class GenericASTTraversal: def __init__(self, ast): self.ast = ast def typestring(self, node): return node.type def prune(self): raise GenericASTTraversalPruningException def preorder(self, node=None): if node is None: node = self.ast try: name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) except GenericASTTraversalPruningException: return for kid in node: self.preorder(kid) name = name + '_exit' if hasattr(self, name): func = getattr(self, name) func(node) def postorder(self, node=None): if node is None: node = self.ast for kid in node: self.postorder(kid) name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) def default(self, node): pass # # GenericASTMatcher. AST nodes must have "__getitem__" and "__cmp__" # implemented. # # XXX - makes assumptions about how GenericParser walks the parse tree. # class GenericASTMatcher(GenericParser): def __init__(self, start, ast): GenericParser.__init__(self, start) self.ast = ast def preprocess(self, rule, func): rebind = lambda func, self=self: \ lambda args, func=func, self=self: \ self.foundMatch(args, func) lhs, rhs = rule rhslist = list(rhs) rhslist.reverse() return (lhs, tuple(rhslist)), rebind(func) def foundMatch(self, args, func): func(args[-1]) return args[-1] def match_r(self, node): self.input.insert(0, node) children = 0 for child in node: if children == 0: self.input.insert(0, '(') children = children + 1 self.match_r(child) if children > 0: self.input.insert(0, ')') def match(self, ast=None): if ast is None: ast = self.ast self.input = [] self.match_r(ast) self.parse(self.input) def resolve(self, list): # # Resolve ambiguity in favor of the longest RHS. # return list[-1] def _dump(tokens, states): for i in range(len(states)): print('state', i) for (lhs, rhs), pos, parent in states[i]: print('\t', lhs, '::='), print(' '.join(rhs[:pos])), print('.'), print(' '.join(rhs[pos:])), print(',', parent, '.', pos) # print(',', parent if i < len(tokens): print('') print('token', str(tokens[i])) print('') pysnmp-apps-0.3.2/pysnmp_apps/cli/pdu.py0000644000014400001440000001761011653232201020376 0ustar ilyausers00000000000000import sys from pyasn1.type import univ from pyasn1.error import PyAsn1Error from pysnmp.proto import rfc1902 from pysnmp import error from pysnmp_apps.cli import base # Read class # Usage def getReadUsage(): return "\ Management parameters:\n\ [\"mib-module\"::]\"object-name\"|\"oid\" ...\n\ mib-module: MIB name (such as SNMPv2-MIB)\n\ object-name: MIB symbol (sysDescr.0) or OID\n\ " # Scanner class ReadPduScannerMixIn: pass # Parser class ReadPduParserMixIn: def p_varBindSpec(self, args): ''' VarBind ::= VarName ''' def p_paramsSpec(self, args): ''' Params ::= VarBinds ''' def p_pduSpec(self, args): ''' VarBinds ::= VarBind whitespace VarBinds VarBinds ::= VarBind VarBinds ::= VarName ::= ModName semicolon semicolon NodeName VarName ::= ModName semicolon semicolon VarName ::= semicolon semicolon NodeName VarName ::= NodeName ModName ::= string NodeName ::= ObjectName ObjectIndices ObjectName ::= string ObjectIndices ::= ObjectIndex string ObjectIndices ObjectIndices ::= ObjectIndex ObjectIndices ObjectIndices ::= ObjectIndex ObjectIndices ::= ObjectIndex ::= quote string quote ''' # Generator class __ReadPduGenerator(base.GeneratorTemplate): def n_ModName(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['modName'] = node[0].attr def n_ObjectName(self, cbCtx, node): snmpEngine, ctx = cbCtx objectName = [] for subOid in node[0].attr.split('.'): if not subOid: continue try: objectName.append(int(subOid)) except ValueError: objectName.append(subOid) ctx['objectName'] = tuple(objectName) def n_ObjectIndex(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'objectIndices' not in ctx: ctx['objectIndices'] = [] ctx['objectIndices'].append(node[1].attr) def n_VarName_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewCtl = ctx['mibViewController'] if 'modName' in ctx: mibViewCtl.mibBuilder.loadModules(ctx['modName']) if 'objectName' in ctx: objectName = ctx['objectName'] else: objectName = None modName = ctx.get('modName', '') if objectName: oid, label, suffix = mibViewCtl.getNodeName(objectName, modName) else: oid, label, suffix = mibViewCtl.getFirstNodeName(modName) if sys.version_info[0] < 3: intTypes = (int, long) else: intTypes = (int,) if [ x for x in suffix if not isinstance(x, intTypes) ]: raise error.PySnmpError( 'Cant resolve object at: %s' % (suffix,) ) modName, nodeDesc, _suffix = mibViewCtl.getNodeLocation(oid) mibNode, = mibViewCtl.mibBuilder.importSymbols(modName, nodeDesc) if not hasattr(self, '_MibTableColumn'): self._MibTableColumn, = mibViewCtl.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTableColumn' ) if isinstance(mibNode, self._MibTableColumn): # Table column if 'objectIndices' in ctx: modName, nodeDesc, _suffix = mibViewCtl.getNodeLocation( mibNode.name[:-1] ) mibNode, = mibViewCtl.mibBuilder.importSymbols( modName, nodeDesc ) suffix = suffix + mibNode.getInstIdFromIndices( *ctx['objectIndices'] ) else: if 'objectIndices' in ctx: raise error.PySnmpError( 'Cant resolve indices: %s' % (ctx['objectIndices'],) ) ctx['varName'] = oid + suffix if 'objectName' in ctx: del ctx['objectName'] if 'objectIndices' in ctx: del ctx['objectIndices'] def n_VarBind_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'varBinds' not in ctx: ctx['varBinds'] = [ (ctx['varName'], None) ] else: ctx['varBinds'].append((ctx['varName'], None)) del ctx['varName'] def n_VarBinds_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'varBinds' not in ctx or not ctx['varBinds']: ctx['varBinds'] = [ ((1, 3, 6), None) ] def readPduGenerator(cbCtx, ast): __ReadPduGenerator().preorder(cbCtx, ast) # Write class def getWriteUsage(): return "\ Management parameters:\n\ <[\"mib-module\"::]\"object-name\"|\"oid\" \"type\"|\"=\" value> ...\n\ mib-module: MIB name (such as SNMPv2-MIB)\n\ object-name: MIB symbol (sysDescr.0) or OID\n\ type: MIB value type\n\ i integer\n\ u unsigned integer\n\ s string\n\ n NULL\n\ o ObjectIdentifier\n\ t TimeTicks\n\ a IP address\n\ =: use MIB for value type lookup\n\ value: value to write\n\ " # Scanner WritePduScannerMixIn = ReadPduScannerMixIn # Parser class WritePduParserMixIn(ReadPduParserMixIn): def p_varBindSpec(self, args): ''' VarBind ::= VarName whitespace VarType whitespace VarValue VarType ::= string VarValue ::= string ''' # Generator class __WritePduGenerator(__ReadPduGenerator): _typeMap = { 'i': rfc1902.Integer(), 'u': rfc1902.Integer32(), 's': rfc1902.OctetString(), 'n': univ.Null(), 'o': univ.ObjectIdentifier(), 't': rfc1902.TimeTicks(), 'a': rfc1902.IpAddress() } def n_VarType(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['varType'] = node[0].attr def n_VarValue(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['varValue'] = node[0].attr def n_VarBind_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewCtl = ctx['mibViewController'] if ctx['varType'] == '=': modName, nodeDesc, suffix = mibViewCtl.getNodeLocation(ctx['varName']) mibNode, = mibViewCtl.mibBuilder.importSymbols(modName, nodeDesc) if hasattr(mibNode, 'syntax'): MibTableColumn, = mibViewCtl.mibBuilder.importSymbols('SNMPv2-SMI', 'MibTableColumn') if isinstance(mibNode, MibTableColumn) or suffix == (0,): val = mibNode.syntax else: raise error.PySnmpError( 'Found MIB scalar %s but non-scalar given %s' % (mibNode.name + (0,), ctx['varName']) ) else: raise error.PySnmpError( 'Variable %s has no syntax' % (ctx['varName'],) ) else: try: val = self._typeMap[ctx['varType']] except KeyError: raise error.PySnmpError('unsupported SNMP value type \"%s\"' % ctx['varType']) try: val = val.clone(ctx['varValue']) except PyAsn1Error: raise error.PySnmpError(sys.exc_info()[1]) if 'varBinds' not in ctx: ctx['varBinds'] = [ (ctx['varName'], val) ] else: ctx['varBinds'].append((ctx['varName'], val)) def writePduGenerator(cbCtx, ast): snmpEngine, ctx = cbCtx __WritePduGenerator().preorder((snmpEngine, ctx), ast) pysnmp-apps-0.3.2/pysnmp_apps/cli/main.py0000644000014400001440000000500211653075402020532 0ustar ilyausers00000000000000from pysnmp.smi import view from pysnmp_apps.cli import base from pysnmp import error, majorVersionId try: from pysnmp import debug except ImportError: debug = None # Usage def getUsage(): return "\ PySNMP library version %s; http://pysnmp.sf.net\n\ -h display this help message\n\ -V software release information\n\ -d dump raw packets\n\ -D category enable debugging [%s]\n\ " % (majorVersionId, debug and ','.join(debug.flagMap.keys()) or "") # Scanner class MainScannerMixIn: def t_help(self, s): r' -h ' self.rv.append(base.ConfigToken('help')) def t_versioninfo(self, s): r' -V ' self.rv.append(base.ConfigToken('versioninfo')) def t_dump(self, s): r' -d ' self.rv.append(base.ConfigToken('dump')) def t_debug(self, s): r' -D ' self.rv.append(base.ConfigToken('debug')) # Parser class MainParserMixIn: initialSymbol = 'Cmdline' def error(self, token): raise error.PySnmpError( 'Command-line parser error at token %s\n' % token ) def p_cmdline(self, args): ''' Cmdline ::= Options Agent whitespace Params ''' def p_cmdlineExt(self, args): ''' Options ::= Option whitespace Options Options ::= Option Options ::= Option ::= Help Option ::= VersionInfo Option ::= DebugOption Help ::= help VersionInfo ::= versioninfo DebugOption ::= Dump DebugOption ::= Debug Dump ::= dump Debug ::= debug string Debug ::= debug whitespace string ''' # Generator class __MainGenerator(base.GeneratorTemplate): # SNMPv1/v2 def n_VersionInfo(self, cbCtx, node): raise error.PySnmpError() def n_Help(self, cbCtx, node): raise error.PySnmpError() def n_Dump(self, cbCtx, node): if debug: debug.setLogger(debug.Debug('io')) def n_Debug(self, cbCtx, node): if debug: if len(node) > 2: f = node[2].attr else: f = node[1].attr debug.setLogger(debug.Debug(*f.split(','))) def generator(cbCtx, ast): snmpEngine, ctx = cbCtx ctx['mibViewController'] = view.MibViewController( snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder ) return __MainGenerator().preorder((snmpEngine, ctx), ast) pysnmp-apps-0.3.2/pysnmp_apps/cli/__init__.py0000644000014400001440000000006110145156462021346 0ustar ilyausers00000000000000# Command-line arguments parsers for pysnmp-apps pysnmp-apps-0.3.2/setup.cfg0000644000014400001440000000007311744502304015735 0ustar ilyausers00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pysnmp-apps-0.3.2/LICENSE0000644000014400001440000000306011732372270015124 0ustar ilyausers00000000000000Copyright (C) 1999-2012, Ilya Etingof , all rights reserved. THIS SOFTWARE IS NOT FAULT TOLERANT AND SHOULD NOT BE USED IN ANY SITUATION ENDANGERING HUMAN LIFE OR PROPERTY. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pysnmp-apps-0.3.2/README0000644000014400001440000000416310435344171015002 0ustar ilyausers00000000000000 PySNMP command-line tools ------------------------- Here is a set of SNMP applications written on top of the PySNMP package (http://sourceforge.net/projects/pysnmp/). Some of these tools mimic their famous Net-SNMP (http://sourceforge.net/projects/net-snmp/) counterparts, while others are designed toward easy integration with other Python applications. PySNMP command-line tools are written entirely in Python and only rely upon PySNMP package to run (PySNMP requires other Python packages). For MIB resolution services to work for popular MIBs, pysnmp-mibs package should be installed as well. These tools have been tested on Linux & Windows XP, though, they might work on any Python-populated system. The whole package is distributed under terms and conditions of BSD-style license. See the LICENSE file for details. INSTALLATION ------------ The pysnmp-apps package is fully distutil'ed, so just type $ python setup.py install to install the whole thing. PySNMP version 4.1.x or later is required to run these tools. OPERATION --------- The most of PySNMP command-line tools could be run in a similar way as their Net-SNMP counterparts. For example: $ pysnmpbulkwalk -v3 -u myuser -l authPriv -A myauthkey -X myprivkey localhost system SNMPv2-MIB::sysDescr.0 = DisplayString: Linux grommit 2.6.16.1 #2 PREEMPT Tue Apr 4 17:04:24 MSD 2006 i686 unknown unknown GNU/Linux SNMPv2-MIB::sysObjectID.0 = ObjectIdentifier: iso.org.dod.internet.private.enterprises.8072.3.2.101.3.6.1.4.1.8072.3.2.10 SNMPv2-MIB::sysUpTime.0 = TimeTicks: 43 days 1:55:47.85372214785 [ skipped ] SNMPv2-MIB::sysORUpTime."8" = TimeStamp: 0 days 0:0:0.77 SNMPv2-MIB::sysORUpTime."9" = TimeStamp: 0 days 0:0:0.77 $ pysnmpget -v3 -u myuser -l authPriv -A myauthkey -X myprivkey localhost IP-MIB::ipAdEntBcastAddr.\"127.0.0.1\" IP-MIB::ipAdEntBcastAddr."127.0.0.1" = Integer32: 1 $ pysnmpset -v2c -c public localhost SNMPv2-MIB::sysDescr.0 = my-new-descr notWritable(17) For more information, please, run any of these tools with --help option. GETTING HELP ------------ Try PySNMP mailing list at http://sourceforge.net/mail/?group_id=14735 =-=-= mailto: ilya@glas.net