pysnmp-apps-0.4.1/0000775006321400632140000000000012657716541015463 5ustar ietingofietingof00000000000000pysnmp-apps-0.4.1/README.txt0000644006321400632140000000436712557353431017163 0ustar ietingofietingof00000000000000 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.3.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: $ snmpbulkwalk.py -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 $ snmpget.py -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 $ snmpset.py -v2c -c public localhost SNMPv2-MIB::sysDescr.0 = my-new-descr notWritable(17) To enjoy MIB resolution features make sure to have PySMI MIB Compiler (http://sf.net/projects/pysmi) installed on your system. 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 pysnmp-apps-0.4.1/requirements.txt0000664006321400632140000000001612602172123020722 0ustar ietingofietingof00000000000000pysnmp>=4.3.0 pysnmp-apps-0.4.1/LICENSE.txt0000644006321400632140000000246212657714074017307 0ustar ietingofietingof00000000000000Copyright (c) 2005-2016, Ilya Etingof All rights reserved. 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. 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 COPYRIGHT HOLDER 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.4.1/pysnmp_apps.egg-info/0000775006321400632140000000000012657716541021526 5ustar ietingofietingof00000000000000pysnmp-apps-0.4.1/pysnmp_apps.egg-info/SOURCES.txt0000664006321400632140000000125712657716541023417 0ustar ietingofietingof00000000000000CHANGES.txt LICENSE.txt MANIFEST.in README.txt requirements.txt setup.cfg 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 scripts/snmpbulkwalk.py scripts/snmpget.py scripts/snmpset.py scripts/snmptranslate.py scripts/snmptrap.py scripts/snmpwalk.pypysnmp-apps-0.4.1/pysnmp_apps.egg-info/top_level.txt0000664006321400632140000000001412657716541024253 0ustar ietingofietingof00000000000000pysnmp_apps pysnmp-apps-0.4.1/pysnmp_apps.egg-info/PKG-INFO0000664006321400632140000000226412657716541022627 0ustar ietingofietingof00000000000000Metadata-Version: 1.1 Name: pysnmp-apps Version: 0.4.1 Summary: SNMP command-line tools Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: A collection of command-line tools for SNMP management purposes built on top of PySNMP package. Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Education Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Telecommunications Industry Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: Topic :: Software Development :: Libraries :: Python Modules pysnmp-apps-0.4.1/pysnmp_apps.egg-info/zip-safe0000664006321400632140000000000112657716541023156 0ustar ietingofietingof00000000000000 pysnmp-apps-0.4.1/pysnmp_apps.egg-info/dependency_links.txt0000664006321400632140000000000112657716541025574 0ustar ietingofietingof00000000000000 pysnmp-apps-0.4.1/pysnmp_apps.egg-info/requires.txt0000664006321400632140000000001612657716541024123 0ustar ietingofietingof00000000000000pysnmp>=4.3.0 pysnmp-apps-0.4.1/setup.cfg0000664006321400632140000000013012657716541017276 0ustar ietingofietingof00000000000000[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pysnmp-apps-0.4.1/CHANGES.txt0000644006321400632140000001264212657715120017267 0ustar ietingofietingof00000000000000Revision 0.4.1, released 12-02-2016 ----------------------------------- - Copyright notice added to non-trivial source code files. - Fix to stray trailing OID lurking to snmp*walk.py output. - Fix to __doc__ use in setup.py to make -O0 installation mode working. Revision 0.4.0, released 28-09-2015 ----------------------------------- - All apps renamed into snmp*.py and moved to scripts/ directory for a more conventional layout. - All apps updated to support the latest pysnmp Standard Applications API. - Initial integration with the PySMI MIB compiler. The -P option now partially supported. All tools try to download missing ASN.1 MIBs from snmplabs.com web site by default. - Conditional variable buildValueOnly replaced with two buildObjectName and buildValue at MibViewProxy. Revision 0.3.4, released 05-10-2013 ----------------------------------- - License updated to vanilla BSD 2-Clause to ease package use (http://opensource.org/licenses/BSD-2-Clause). - Upper level exception handling improved for all apps. - Distribute is gone, switched to setuptools completely. - Fix to config.addTargetAddr() invocation -- since pysnmp 4.2.3, reworked pysnmp LCD model does not require tagging transport address to bind it with communityName. Revision 0.3.3, released 30-01-2013 ----------------------------------- - Tools will report pysnmp-apps package version along with pysnmp version being used. - Package meta-information updated. - Package version is now in __init__.__version__ Revision 0.3.2, released 21-04-2012 ----------------------------------- - MIB path mangiling reworked - Fix to make pysnmptrap INFORM C/L switch operational Revision 0.3.1, released 06-11-2011 ----------------------------------- - 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.4.1/setup.py0000644006321400632140000000615012657714074017174 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # """SNMP command-line tools A collection of command-line tools for SNMP management purposes built on top of PySNMP package. """ import sys classifiers = """\ Development Status :: 5 - Production/Stable Environment :: Console Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Information Technology Intended Audience :: System Administrators Intended Audience :: Telecommunications Industry License :: OSI Approved :: BSD License Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 3 Topic :: Communications Topic :: Software Development :: Libraries :: Python Modules Topic :: System :: Monitoring Topic :: System :: Networking :: Monitoring Topic :: Software Development :: Libraries :: Python Modules """ 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 https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py python ez_setup.py Then you could make eggs from this package. """) if sys.version_info[:2] < (2, 4): print("ERROR: this package requires Python 2.4 or later!") sys.exit(1) try: from setuptools import setup params = {'install_requires': [ 'pysnmp>=4.3.0' ], 'zip_safe': True} except ImportError: for arg in sys.argv: if 'egg' in arg: howto_install_setuptools() sys.exit(1) from distutils.core import setup params = {} if sys.version_info[:2] > (2, 4): params['requires'] = [ 'pysnmp(>=4.3.0)' ] doclines = [x.strip() for x in (__doc__ or '').split('\n') if x] params.update( {'name': 'pysnmp-apps', 'version': open('pysnmp_apps/__init__.py').read().split('\'')[1], 'description': doclines[0], 'long_description': ' '.join(doclines[1:]), 'maintainer': 'Ilya Etingof ', 'author': 'Ilya Etingof', 'author_email': 'ilya@glas.net', 'url': 'http://sourceforge.net/projects/pysnmp/', 'classifiers': [ x for x in classifiers.split('\n') if x ], 'platforms': ['any'], 'license': 'BSD', 'packages': ['pysnmp_apps', 'pysnmp_apps.cli'], 'scripts': ['scripts/snmpget.py', 'scripts/snmpset.py', 'scripts/snmpwalk.py', 'scripts/snmpbulkwalk.py', 'scripts/snmptrap.py', 'scripts/snmptranslate.py']} ) 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.*' ], 'bundle_files': 1, 'compressed': True } } params['zipfile'] = None print("!!! Make sure your pysnmp/pyasn1 packages are NOT .egg'ed!!!") setup(**params) pysnmp-apps-0.4.1/scripts/0000775006321400632140000000000012657716541017152 5ustar ietingofietingof00000000000000pysnmp-apps-0.4.1/scripts/snmpwalk.py0000755006321400632140000001207212657714074021362 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # GETNEXT command generator # import sys, time, traceback 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) # Run SNMP engine def cbFun(snmpEngine, 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 += 1 if cbCtx['myHeadVars'][colIdx].isPrefixOf(oid): sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val ) ) inTableFlag += 1 if cbCtx.get('reportFoundVars'): cbCtx['reportFoundVars'] += inTableFlag if not inTableFlag: return # stop on end-of-table return 1 # continue walking 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) ctx['myHeadVars'] = [ rfc1902.ObjectName(x[0]) for x in ctx['varBinds'] ] cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx['varBinds'], cbFun, ctx ) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1]) for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) 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.4.1/scripts/snmpbulkwalk.py0000755006321400632140000001333712657714074022245 0ustar ietingofietingof00000000000000#!/usr/bin/env python # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # GETBULK command generator # import sys, time, traceback 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) def cbFun(snmpEngine, 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 += 1 if cbCtx['myHeadVars'][colIdx].isPrefixOf(oid): sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val ) ) inTableFlag += 1 if cbCtx.get('reportFoundVars'): cbCtx['reportFoundVars'] += inTableFlag if not inTableFlag: return # stop on end-of-table return 1 # continue walking # Run SNMP engine 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) ctx['myHeadVars'] = [ rfc1902.ObjectName(x[0]) for x in ctx['varBinds'] ] cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx.get('nonRepeaters', 0), ctx.get('maxRepetitions', 25), ctx['varBinds'], cbFun, ctx ) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1]) for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) 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.4.1/scripts/snmptranslate.py0000755006321400632140000001467312657714074022432 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # Command-line MIB browser # import sys, traceback from pyasn1.type import univ from pysnmp.entity import engine from pysnmp.proto import rfc3412 from pysnmp.smi import builder 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\n%s ::= { %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 snmpEngine = engine.SnmpEngine() # Load up MIB texts (DESCRIPTION, etc.) mibBuilder = snmpEngine.getMibBuilder() mibBuilder.loadTexts = True 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 KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1]) for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) sys.exit(-1) ctx['mibViewProxy'].buildValue = 0 # disable value printout 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 pysnmp-apps-0.4.1/scripts/snmptrap.py0000755006321400632140000001671512657714074021402 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # Notificaton Originator # import sys, socket, time, traceback from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.proxy import rfc2576 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_TrapOid(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['TrapOid'] = node[0].attr def n_TrapV1Params_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx # 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']) ctx['pdu'] = rfc2576.v1ToV2(v1Pdu) def n_TrapV2cParams_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'informMode' in ctx: pdu = v2c.InformRequestPDU() v2c.apiPDU.setDefaults(pdu) else: pdu = v2c.TrapPDU() v2c.apiTrapPDU.setDefaults(pdu) v2c.apiPDU.setVarBinds( pdu, [ ( v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), v2c.TimeTicks(ctx['Uptime'])), ( v2c.ObjectIdentifier('1.3.6.1.6.3.1.1.4.1.0'), v2c.ObjectIdentifier(ctx['TrapOid']) ) ] ) ctx['pdu'] = pdu def generator(cbCtx, ast): snmpEngine, ctx = cbCtx return __Generator().preorder((snmpEngine, ctx), ast) # Run SNMP engine def cbFun(snmpEngine, notificationHandle, errorIndication, pdu, cbCtx): if errorIndication: sys.stderr.write('%s\n' % errorIndication) return errorStatus = v2c.apiPDU.getErrorStatus(pdu) if errorStatus: errorIndex = v2c.apiPDU.getErrorIndex(pdu) sys.stderr.write( '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) return for oid, val in v2c.apiPDU.getVarBinds(pdu): sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal( cbCtx['mibViewController'], oid, val ) ) 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) v2c.apiPDU.setVarBinds( ctx['pdu'], v2c.apiPDU.getVarBinds(ctx['pdu']) + ctx['varBinds'] ) ntforg.NotificationOriginator().sendPdu( snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx['pdu'], cbFun, ctx ) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1]) for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) sys.exit(-1) pysnmp-apps-0.4.1/scripts/snmpget.py0000755006321400632140000000572412657714074021211 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # GET command generator # import sys,traceback 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 def cbFun(snmpEngine, 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 ) ) # Run SNMP engine 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) cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx['varBinds'], cbFun, ctx ) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated\n') for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) sys.exit(-1) pysnmp-apps-0.4.1/scripts/snmpset.py0000755006321400632140000000575512657714074021231 0ustar ietingofietingof00000000000000#!/usr/bin/env python # # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # SET command generator # import sys, traceback 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 # Run SNMP engine def cbFun(snmpEngine, 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 ) ) 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) cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx['varBinds'], cbFun, ctx ) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1]) for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';')) sys.exit(-1) pysnmp-apps-0.4.1/pysnmp_apps/0000775006321400632140000000000012657716541020034 5ustar ietingofietingof00000000000000pysnmp-apps-0.4.1/pysnmp_apps/error.py0000644006321400632140000000034612657714074021537 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # from pysnmp import error class SnmpApplicationError(error.PySnmpError): pass pysnmp-apps-0.4.1/pysnmp_apps/cli/0000775006321400632140000000000012657716541020603 5ustar ietingofietingof00000000000000pysnmp-apps-0.4.1/pysnmp_apps/cli/secmod.py0000644006321400632140000002223312657714074022426 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # from 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 BOOTS,TIME destination SNMP engine boots/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 if ',' in ctx['engineBoots']: ctx['engineBoots'], ctx['engineTime'] = ctx['engineBoots'].split(',', 1) else: ctx['engineTime'] = 0 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'] ) # edit SNMP engine boots/uptime if 'engineBoots' in ctx: snmpEngineBoots, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') snmpEngineBoots.setSyntax( snmpEngineBoots.getSyntax().clone(ctx['engineBoots']) ) if 'engineTime' in ctx: snmpEngineTime, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineTime') snmpEngineTime.setSyntax( snmpEngineTime.getSyntax().clone(ctx['engineTime']) ) 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.4.1/pysnmp_apps/cli/spark.py0000644006321400632140000003412612657714074022300 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # 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.4.1/pysnmp_apps/cli/base.py0000644006321400632140000000767012657714074022076 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # 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.4.1/pysnmp_apps/cli/pdu.py0000644006321400632140000002004012657714074021736 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # import 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.4.1/pysnmp_apps/cli/mibview.py0000644006321400632140000003513612657714074022624 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # # 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, compiler from pysnmp import error defaultMibSourceUrl = 'http://mibs.snmplabs.com/asn1/@mib@' defaultMibBorrowerUrl = 'http://mibs.snmplabs.com/pysnmp/fulltexts/@mib@' # Usage def getUsage(): return "\ MIB options:\n\ -m MIB[:...] load given list of MIBs (ALL loads all compiled MIBs)\n\ -M DIR[:...] look in given list of directories for MIBs\n\ -P MIBOPTS Toggle various defaults controlling MIB parsing:\n\ XS: search for ASN.1 MIBs in remote directories specified\n\ in URL form. The @mib@ token in the URL is substituted\n\ with actual MIB to be downloaded. Default repository\n\ address is %s\n\ XB: search for pysnmp MIBs in remote directories specified\n\ in URL form. The @mib@ token in the URL is substituted\n\ with actual MIB to be downloaded. Default repository\n\ address is %s\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\ " % (defaultMibSourceUrl, defaultMibBorrowerUrl) # 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_parseropts(self, s): r' -P ' self.rv.append(base.ConfigToken('parseropts')) 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 ::= ParserOption 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 ParserOption ::= parseropts string ParserOption ::= parseropts whitespace string ParserOption ::= parseropts string whitespace Url ParserOption ::= parseropts whitespace string whitespace Url Url ::= string semicolon 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.getMibBuilder() if node[0].attr.lower() == 'all': mibBuilder.loadModules() else: mibBuilder.loadModules(node[0].attr) def n_MibDir(self, cbCtx, node): snmpEngine, ctx = cbCtx if 'MibDir' not in ctx: ctx['MibDir'] = [] ctx['MibDir'].append(node[0].attr) def n_Url(self, cbCtx, node): snmpEngine, ctx = cbCtx ctx['Url'] = node[0].attr+':'+node[2].attr def n_ParserOption_exit(self, cbCtx, node): snmpEngine, ctx = cbCtx opt = node[1].attr or node[2].attr for c in opt: if c == 'XS': if 'MibDir' not in ctx: ctx['MibDir'] = [] if 'Url' not in ctx: raise error.PySnmpError('Missing URL for option') ctx['MibDir'].append(ctx['Url']) del ctx['Url'] elif c == 'XB': if 'MibBorrowers' not in ctx: ctx['MibBorrowers'] = [] if 'Url' not in ctx: raise error.PySnmpError('Missing URL for option') ctx['MibBorrowers'].append(ctx['Url']) del ctx['Url'] def n_OutputOption(self, cbCtx, node): snmpEngine, ctx = cbCtx mibViewProxy = ctx['mibViewProxy'] opt = node[1].attr or node[2].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.buildObjectName = 0 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'] opt = node[1].attr or node[2].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']) compiler.addMibCompiler(snmpEngine.getMibBuilder()) snmpEngine, ctx = __MibViewGenerator().preorder((snmpEngine, ctx), ast) if 'MibDir' not in ctx: ctx['MibDir'] = [ defaultMibSourceUrl ] if 'MibBorrowers' not in ctx: ctx['MibBorrowers'] = [ defaultMibBorrowerUrl ] compiler.addMibCompiler(snmpEngine.getMibBuilder(), sources=ctx['MibDir'], borrowers=ctx['MibBorrowers']) return snmpEngine, ctx 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 buildObjectName = 1 buildValue = 1 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 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 self.buildObjectName: 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.buildObjectName and self.buildValue: if self.buildEqualSign: out = out + ' = ' else: out = out + ' ' # Value if self.buildValue: 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.4.1/pysnmp_apps/cli/main.py0000644006321400632140000000665612657714074022113 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # import sys from pysnmp.smi import view from pysnmp_apps.cli import base from pysnmp import error from pysnmp_apps import __version__ as pysnmpAppsVersion try: from pysnmp import __version__ as pysnmpVersion except ImportError: pysnmpVersion = 'N/A' try: from pysmi import __version__ as pysmiVersion except ImportError: pysmiVersion = 'N/A' try: from pysnmp_mibs import __version__ as pysnmpMibsVersion except ImportError: pysnmpMibsVersion = 'N/A' try: from pyasn1 import __version__ as pyasn1Version except ImportError: pyasn1Version = 'N/A' try: from pysnmp import debug except ImportError: debug = None # Usage def getUsage(): return "\ Command-line SNMP tools version %s, written by Ilya Etingof \n\ Foundation libraries: pysmi %s, pysnmp %s, pysnmp-mibs %s, pyasn1 %s\n\ Python interpreter: %s\n\ Software documentation and support at 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\ " % ( pysnmpAppsVersion, pysmiVersion, pysnmpVersion, pysnmpMibsVersion, pyasn1Version, sys.version.replace('\n', ''), debug and ','.join(debug.flagMap.keys()) or "") # Scanner class MainScannerMixIn: def t_help(self, s): r' -h|--help ' self.rv.append(base.ConfigToken('help')) def t_versioninfo(self, s): r' -V|--version ' 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|--debug ' 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.getMibBuilder() ) return __MainGenerator().preorder((snmpEngine, ctx), ast) pysnmp-apps-0.4.1/pysnmp_apps/cli/__init__.py0000644006321400632140000000007311775063464022711 0ustar ietingofietingof00000000000000# This file is necessary to make this directory a package. pysnmp-apps-0.4.1/pysnmp_apps/cli/msgmod.py0000644006321400632140000000261612657714074022445 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # from 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.4.1/pysnmp_apps/cli/target.py0000644006321400632140000001434312657714074022445 0ustar ietingofietingof00000000000000# # This file is part of pysnmp-apps software. # # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # import 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'] 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.get('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.4.1/pysnmp_apps/__init__.py0000644006321400632140000000010112621416111022110 0ustar ietingofietingof00000000000000# http://www.python.org/dev/peps/pep-0396/ __version__ = '0.4.1' pysnmp-apps-0.4.1/MANIFEST.in0000644006321400632140000000005512546160144017204 0ustar ietingofietingof00000000000000include *.txt recursive-include scripts *.py pysnmp-apps-0.4.1/PKG-INFO0000664006321400632140000000226412657716541016564 0ustar ietingofietingof00000000000000Metadata-Version: 1.1 Name: pysnmp-apps Version: 0.4.1 Summary: SNMP command-line tools Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: A collection of command-line tools for SNMP management purposes built on top of PySNMP package. Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Education Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Telecommunications Industry Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: Topic :: Software Development :: Libraries :: Python Modules