[Python-modules-commits] r420 - in /packages/python-pysnmp4-apps:
./ branches/ branches/upstream/
branches/upstream/current/ branches/upstream/current/pysnmp_apps/
branches/upstream/current/pysnmp_apps/v4/
branches/upstream/current/pysnmp_apps/v4/cli/
branches/upstream/current/tools/ tags/
jluebbe-guest at users.alioth.debian.org
jluebbe-guest at users.alioth.debian.org
Fri May 5 06:12:05 UTC 2006
Author: jluebbe-guest
Date: Fri May 5 06:11:08 2006
New Revision: 420
URL: http://svn.debian.org/wsvn/python-modules/?sc=1&rev=420
Log:
[svn-inject] Installing original source of python-pysnmp4-apps
Added:
packages/python-pysnmp4-apps/
packages/python-pysnmp4-apps/branches/
packages/python-pysnmp4-apps/branches/upstream/
packages/python-pysnmp4-apps/branches/upstream/current/
packages/python-pysnmp4-apps/branches/upstream/current/CHANGES
packages/python-pysnmp4-apps/branches/upstream/current/LICENSE
packages/python-pysnmp4-apps/branches/upstream/current/MANIFEST
packages/python-pysnmp4-apps/branches/upstream/current/PKG-INFO
packages/python-pysnmp4-apps/branches/upstream/current/README
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/__init__.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/__init__.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/__init__.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/base.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/main.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/mibview.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/msgmod.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/pdu.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/secmod.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/spark.py
packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/target.py
packages/python-pysnmp4-apps/branches/upstream/current/setup.py
packages/python-pysnmp4-apps/branches/upstream/current/tools/
packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk (with props)
packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget (with props)
packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset (with props)
packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk (with props)
packages/python-pysnmp4-apps/tags/
Added: packages/python-pysnmp4-apps/branches/upstream/current/CHANGES
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/CHANGES?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/CHANGES (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/CHANGES Fri May 5 06:11:08 2006
@@ -1,0 +1,57 @@
+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.
Added: packages/python-pysnmp4-apps/branches/upstream/current/LICENSE
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/LICENSE?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/LICENSE (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/LICENSE Fri May 5 06:11:08 2006
@@ -1,0 +1,28 @@
+Copyright (C) 1999-2005, Ilya Etingof <ilya at glas.net>, all rights reserved.
+
+THIS SOFTWARE IS NOT FAULT TOLERANT AND SHOULD NOT BE USED IN ANY SITUATION
+ENDANGERING HUMAN LIFE OR PROPERTY.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * The name of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Added: packages/python-pysnmp4-apps/branches/upstream/current/MANIFEST
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/MANIFEST?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/MANIFEST (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/MANIFEST Fri May 5 06:11:08 2006
@@ -1,0 +1,20 @@
+MANIFEST
+CHANGES
+LICENSE
+README
+pysnmp_apps/v4/cli/pdu.py
+pysnmp_apps/v4/cli/__init__.py
+pysnmp_apps/v4/cli/base.py
+pysnmp_apps/v4/cli/mibview.py
+pysnmp_apps/v4/cli/spark.py
+pysnmp_apps/v4/cli/target.py
+pysnmp_apps/v4/cli/secmod.py
+pysnmp_apps/v4/cli/msgmod.py
+pysnmp_apps/v4/cli/main.py
+pysnmp_apps/v4/__init__.py
+pysnmp_apps/__init__.py
+tools/pysnmpget
+tools/pysnmpwalk
+tools/pysnmpset
+tools/pysnmpbulkwalk
+setup.py
Added: packages/python-pysnmp4-apps/branches/upstream/current/PKG-INFO
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/PKG-INFO?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/PKG-INFO (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/PKG-INFO Fri May 5 06:11:08 2006
@@ -1,0 +1,10 @@
+Metadata-Version: 1.0
+Name: pysnmp-apps
+Version: 0.2.3a
+Summary: PySNMP applications
+Home-page: http://sourceforge.net/projects/pysnmp/
+Author: Ilya Etingof
+Author-email: ilya at glas.net
+License: BSD
+Description: UNKNOWN
+Platform: UNKNOWN
Added: packages/python-pysnmp4-apps/branches/upstream/current/README
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/README?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/README (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/README Fri May 5 06:11:08 2006
@@ -1,0 +1,59 @@
+
+PySNMP command-line tools
+-------------------------
+
+Here is a set of SNMP applications written on top of the PySNMP package
+(http://sourceforge.net/projects/pysnmp/). Some of these tools mimic
+their famous Net-SNMP (http://sourceforge.net/projects/net-snmp/)
+counterparts, while others are designed toward easy integration with
+other Python applications.
+
+PySNMP command-line tools are written entirely in Python and only rely
+upon PySNMP package to run (PySNMP requires other Python packages). For
+MIB resolution services to work for popular MIBs, pysnmp-mibs package
+should be installed as well.
+
+These tools have been tested on Linux & Windows XP, though, they might work
+on any Python-populated system.
+
+The whole package is distributed under terms and conditions of BSD-style
+license. See the LICENSE file for details.
+
+INSTALLATION
+------------
+
+The pysnmp-apps package is fully distutil'ed, so just type
+
+$ python setup.py install
+
+to install the whole thing.
+
+PySNMP version 4.1.x or later is required to run these tools.
+
+OPERATION
+---------
+
+The most of PySNMP command-line tools could be run in a similar way as
+their Net-SNMP counterparts. For example:
+
+$ pysnmpbulkwalk -v3 -u myuser -l authPriv -A myauthkey -X myprivkey localhost system
+SNMPv2-MIB::sysDescr.0 = DisplayString: Linux cray.glas.net 2.4.20-13.8 #1 Mon May 12 12:20:54 EDT 2003 i686
+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 = SysUpTime: 43 days 1:55:47.85372214785
+^C
+
+$ pysnmpget -v3 -u myuser -l authPriv -A myauthkey -X myprivkey localhost IP-MIB::ipAdEntBcastAddr.\"127.0.0.1\"
+IP-MIB::ipAdEntBcastAddr."127.0.0.1" = Integer32: 1
+
+$ pysnmpset -v2c -c public localhost SNMPv2-MIB::sysDescr.0 = my-new-descr
+notWritable(17)
+
+For more information, please, run any of these tools with --help option.
+
+GETTING HELP
+------------
+
+Try PySNMP mailing list at http://sourceforge.net/mail/?group_id=14735
+
+=-=-=
+mailto: ilya at glas.net
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/__init__.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/__init__.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/__init__.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/__init__.py Fri May 5 06:11:08 2006
@@ -1,0 +1,28 @@
+"""Various components of SNMP applications"""
+import os
+import sys
+import string
+
+def switchApiVersion(subPkg):
+ pkg = os.path.split(__path__[0])[-1]
+ newMod = __import__(subPkg, globals(), locals(), pkg)
+ realPkg = '_real_' + pkg
+ if sys.modules.has_key(realPkg):
+ sys.modules[pkg] = sys.modules[realPkg]
+ sys.modules[realPkg] = sys.modules[pkg]
+ sys.modules[pkg] = newMod
+
+def __isSubPackage(subDir):
+ if subDir and subDir[0] == 'v' and subDir[1] in string.digits \
+ and len(subDir) == 2:
+ return 1
+
+subDirs = filter(__isSubPackage, os.listdir(__path__[0]))
+subDirs.sort(); subDirs.reverse()
+
+if os.environ.has_key('PYSNMP_API_VERSION'):
+ v = os.environ['PYSNMP_API_VERSION']
+ if v:
+ switchApiVersion(v) # do not load any API
+else:
+ switchApiVersion(subDirs[-1]) # take the most recent version
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/__init__.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/__init__.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/__init__.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/__init__.py Fri May 5 06:11:08 2006
@@ -1,0 +1,1 @@
+"""Various components of SNMP applications"""
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/__init__.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/__init__.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/__init__.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/__init__.py Fri May 5 06:11:08 2006
@@ -1,0 +1,1 @@
+# Command-line arguments parsers for pysnmp-apps
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/base.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/base.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/base.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/base.py Fri May 5 06:11:08 2006
@@ -1,0 +1,118 @@
+# Abstract interface to SNMP objects initializers
+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 __cmp__(self, o):
+ return cmp(self.type, o)
+ 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)
+ def __setslice__(self, low, high, seq):
+ self._kids[low:high] = seq
+ def __cmp__(self, o):
+ return cmp(self.type, o)
+ 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' [=\.a-zA-Z0-9\///-][\.a-zA-Z0-9\///-]* '
+ self.rv.append(ConfigToken('string', s))
+
+class __SecondLevelScanner(__FirstLevelScanner):
+ def t_semicolon(self, s):
+ r' : '
+ self.rv.append(ConfigToken('semicolon'))
+
+ 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)
+
+ def nonterminal2(self, type, args):
+ # Flatten AST a bit by not making nodes if there's only
+ # one child.
+ if len(args) == 1:
+ return args[0]
+ return spark.GenericASTBuilder.nonterminal(self, type, args)
+
+
+# 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
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/main.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/main.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/main.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/main.py Fri May 5 06:11:08 2006
@@ -1,0 +1,64 @@
+from pysnmp.smi import view
+from pysnmp_apps.cli import base
+from pysnmp import error, majorVersionId
+
+# Usage
+
+def getUsage():
+ return "\
+PySNMP library version %s; http://pysnmp.sf.net\n\
+ -h display this help message\n\
+ -V software release information\n\
+" % majorVersionId
+
+# Scanner
+
+class MainScannerMixIn:
+ def t_help(self, s):
+ r' -h '
+ self.rv.append(base.ConfigToken('help'))
+
+ def t_versioninfo(self, s):
+ r' -V '
+ self.rv.append(base.ConfigToken('versioninfo'))
+
+# 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
+
+ Options ::= Option whitespace Options
+ Options ::= Option
+ Options ::=
+
+ Option ::= Help
+ Option ::= VersionInfo
+
+ Help ::= help
+
+ VersionInfo ::= versioninfo
+ '''
+# Generator
+
+class __MainGenerator(base.GeneratorTemplate):
+ # SNMPv1/v2
+ def n_VersionInfo(self, (snmpEngine, ctx), node):
+ raise error.PySnmpError()
+
+ def n_Help(self, (snmpEngine, ctx), node):
+ raise error.PySnmpError()
+
+def generator((snmpEngine, ctx), ast):
+ ctx['mibViewController'] = view.MibViewController(
+ snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
+ )
+ return __MainGenerator().preorder((snmpEngine, ctx), ast)
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/mibview.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/mibview.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/mibview.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/mibview.py Fri May 5 06:11:08 2006
@@ -1,0 +1,329 @@
+# C/L interface to MIB variables. Mimics Net-SNMP CLI.
+import os, string
+from pyasn1.type import univ
+from pysnmp_apps.cli import base
+from pysnmp.proto import rfc1902
+from pysnmp import error
+
+# Usage
+
+def getUsage():
+ return "\
+MIB options:\n\
+ -m MIB[:...] load given list of MIBs (ALL loads everything)\n\
+ -M DIR[:...] look in given list of directories for MIBs\n\
+ -O OUTOPTS Toggle various defaults controlling output display:\n\
+ q: removes the equal sign and type information\n\
+ Q: removes the type information\n\
+ f: print full OIDs on output\n\
+ s: print only last symbolic element of OID\n\
+ S: print MIB module-id plus last element\n\
+ u: print OIDs using UCD-style prefix suppression\n\
+ n: print OIDs numerically\n\
+ e: print enums numerically\n\
+ b: do not break OID indexes down\n\
+ E: include a \" to escape the quotes in indices\n\
+ X: place square brackets around each index\n\
+ T: print value in hex\n\
+ v: print values only (not OID = value)\n\
+ U: don't print units\n\
+ t: output timeticks values as raw numbers\n\
+ -I INOPTS Toggle various defaults controlling input parsing:\n\
+ h: don't apply DISPLAY-HINTs\n\
+ u: top-level OIDs must have '.' prefix (UCD-style)\n\
+"
+
+# Scanner
+
+class MibViewScannerMixIn:
+ def t_mibfiles(self, s):
+ r' -m '
+ self.rv.append(base.ConfigToken('mibfiles'))
+
+ def t_mibdirs(self, s):
+ r' -M '
+ self.rv.append(base.ConfigToken('mibdirs'))
+
+ def t_outputopts(self, s):
+ r' -O '
+ self.rv.append(base.ConfigToken('outputopts'))
+
+ def t_inputopts(self, s):
+ r' -I '
+ self.rv.append(base.ConfigToken('inputopts'))
+
+# Parser
+
+class MibViewParserMixIn:
+ def p_mibView(self, args):
+ '''
+ Option ::= GeneralOption
+ Option ::= OutputOption
+ Option ::= InputOption
+
+ GeneralOption ::= MibDirList
+ MibDirList ::= mibdirs MibDirs
+ MibDirList ::= mibdirs whitespace MibDirs
+ MibDirs ::= MibDir semicolon MibDirs
+ MibDirs ::= MibDir
+ MibDir ::= string
+ GeneralOption ::= MibFileList
+ MibFileList ::= mibfiles MibFiles
+ MibFileList ::= mibfiles whitespace MibFiles
+ MibFiles ::= MibFile semicolon MibFiles
+ MibFiles ::= MibFile
+ MibFile ::= string
+
+ OutputOption ::= outputopts string
+ OutputOption ::= outputopts whitespace string
+
+ InputOption ::= inputopts string
+ InputOption ::= inputopts whitespace string
+ '''
+
+# Generator
+
+class __MibViewGenerator(base.GeneratorTemplate):
+ # Load MIB modules
+ def n_MibFile(self, (snmpEngine, ctx), node):
+ mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
+ if string.lower(node[0].attr) == 'all':
+ mibBuilder.loadModules()
+ else:
+ mibBuilder.loadModules(node[0].attr)
+
+ def n_MibDir(self, (snmpEngine, ctx), node):
+ mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
+ apply(mibBuilder.setMibPath, (node[0].attr,) + mibBuilder.getMibPath())
+
+ def n_OutputOption(self, (snmpEngine, ctx), node):
+ mibViewProxy = ctx['mibViewProxy']
+ if len(node) > 2:
+ opt = node[2].attr
+ else:
+ opt = node[1].attr
+ for c in map(None, opt):
+ if c == 'q':
+ mibViewProxy.buildEqualSign = 0
+ mibViewProxy.buildTypeInfo = 0
+ elif c == 'Q':
+ mibViewProxy.buildTypeInfo = 0
+ elif c == 'f':
+ mibViewProxy.buildModInfo = 0
+ mibViewProxy.buildObjectDesc = 0
+ mibViewProxy.buildAbsoluteName = 1
+ elif c == 's':
+ mibViewProxy.buildModInfo = 0
+ mibViewProxy.buildObjectDesc = 1
+ elif c == 'S':
+ mibViewProxy.buildObjectDesc = 1
+ elif c == 'u':
+ pass
+ elif c == 'n':
+ mibViewProxy.buildObjectDesc = 0
+ mibViewProxy.buildModInfo = 0
+ mibViewProxy.buildNumericName = 1
+ mibViewProxy.buildNumericIndices = 1
+ mibViewProxy.buildAbsoluteName = 1
+ elif c == 'e':
+ raise error.PySnmpError('Option not implemented')
+ elif c == 'b':
+ mibViewProxy.buildNumericIndices = 1
+ elif c == 'E':
+ mibViewProxy.buildEscQuotes = 1
+ elif c == 'X':
+ mibViewProxy.buildSquareBrackets = 1
+ elif c == 'T':
+ mibViewProxy.buildHexVals = 1
+ elif c == 'v':
+ mibViewProxy.buildValueOnly = 1
+ elif c == 'U':
+ mibViewProxy.buildUnits = 0
+ elif c == 't':
+ mibViewProxy.buildRawTimeTicks = 1
+ pass
+ elif c == 'R':
+ mibViewProxy.buildRawVals = 1
+ else:
+ raise error.PySnmpError(
+ 'Unknown output option %s at %s' % (c, self)
+ )
+
+ def n_InputOption(self, (snmpEngine, ctx), node):
+ mibViewProxy = ctx['mibViewProxy']
+ if len(node) > 2:
+ opt = node[2].attr
+ else:
+ opt = node[1].attr
+ for c in map(None, 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((snmpEngine, ctx), ast):
+ ctx['mibViewProxy'] = MibViewProxy(ctx['mibViewController'])
+ return __MibViewGenerator().preorder((snmpEngine, ctx), ast)
+
+# Proxy MIB view
+
+class MibViewProxy:
+ # Defaults
+ defaultOidPrefix = (
+ 'iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system'
+ )
+ defaultMibs = ('SNMPv2-MIB',)
+ defaultMibDirs = ()
+
+ # MIB parsing options
+ # currently N/A
+
+ # MIB output options
+ buildModInfo = 1
+ buildObjectDesc = 1
+ buildNumericName = 0
+ buildAbsoluteName = 0
+ buildNumericIndices = 0
+ buildEqualSign = 1
+ buildTypeInfo = 1
+ buildEscQuotes = 0
+ buildSquareBrackets = 0
+ buildHexVals = 0
+ buildRawVals = 0
+ buildRawTimeTicks = 0
+ buildGuessedStringVals = 1
+ buildValueOnly = 0
+ buildUnits = 1
+
+ # MIB input options
+ parseAsRandomAccessMib = 1
+ parseAsRegExp = 0
+ parseAsRelativeOid = 1
+ parseAndCheckIndices = 1
+ parseAsDisplayHint = 1
+
+ def __init__(self, mibViewController):
+ if os.environ.has_key('PYSNMPOIDPREFIX'):
+ self.defaultOidPrefix = os.environ['PYSNMPOIDPREFIX']
+ if os.environ.has_key('PYSNMPMIBS'):
+ self.defaultMibs = string.split(os.environ['PYSNMPMIBS'], ':')
+ if os.environ.has_key('PYSNMPMIBDIRS'):
+ self.defaultMibDirs = string.split(os.environ['MIBDIRS'], ':')
+ if self.defaultMibDirs:
+ apply(mibViewController.mibBuilder.setMibPath,
+ (self.defaultMibDirs) + \
+ mibViewController.mibBuilder.getMibPath())
+ if self.defaultMibs:
+ apply(mibViewController.mibBuilder.loadModules,
+ self.defaultMibs)
+ self.__oidValue = univ.ObjectIdentifier()
+ self.__intValue = univ.Integer()
+ self.__timeValue = rfc1902.TimeTicks()
+
+ def getPrettyOidVal(self, mibViewController, oid, val):
+ prefix, label, suffix = mibViewController.getNodeName(oid)
+ modName, nodeDesc, _suffix = mibViewController.getNodeLocation(prefix)
+ out = ''
+ # object name
+ if not self.buildValueOnly:
+ if self.buildModInfo:
+ out = '%s::' % modName
+ if self.buildObjectDesc:
+ out = out + nodeDesc
+ else:
+ if self.buildNumericName:
+ name = prefix
+ else:
+ name = label
+ if not self.buildAbsoluteName:
+ name = name[len(self.defaultOidPrefix):]
+ out = out + string.join(map(lambda x: str(x), 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+'.'+string.join(
+ map(lambda x: str(x), 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 + '.' + string.join(
+ map(lambda x: str(x), suffix), '.'
+ )
+ if self.buildEqualSign:
+ out = out + ' = '
+ else:
+ out = out + ' '
+ # Value
+ mibNode, = mibViewController.mibBuilder.importSymbols(
+ modName, nodeDesc
+ )
+ if hasattr(mibNode, 'syntax'):
+ syntax = mibNode.syntax
+ else:
+ syntax = val
+ 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 + repr(int(val))
+ elif self.__oidValue.isSuperTypeOf(val):
+ out = out + repr(tuple(val))
+ else:
+ out = out + repr(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 + string.join(
+ label+tuple(map(lambda x: str(x), suffix)), '.'
+ )
+
+ 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
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/msgmod.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/msgmod.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/msgmod.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/msgmod.py Fri May 5 06:11:08 2006
@@ -1,0 +1,52 @@
+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, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ versionId = node[2].attr
+ else:
+ versionId = node[1].attr
+ if self._versionIdMap.has_key(versionId):
+ ctx['versionId'] = self._versionIdMap[versionId]
+ else:
+ raise error.PySnmpError('Bad version value %s' % versionId)
+
+def generator((snmpEngine, ctx), ast):
+ __MPGenerator().preorder((snmpEngine, ctx), ast)
+ # Commit defaults
+ if not ctx.has_key('versionId'):
+ ctx['versionId'] = 3
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/pdu.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/pdu.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/pdu.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/pdu.py Fri May 5 06:11:08 2006
@@ -1,0 +1,223 @@
+import string, types
+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
+ VarType ::= string
+ VarValue ::= string
+ '''
+
+ def p_pduSpec(self, args):
+ '''
+ Params ::= VarBinds
+
+ 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, (snmpEngine, ctx), node):
+ ctx['modName'] = node[0].attr
+
+ def n_ObjectName(self, (snmpEngine, ctx), node):
+ objectName = []
+ for subOid in string.split(node[0].attr, '.'):
+ if not subOid:
+ continue
+ try:
+ objectName.append(string.atol(subOid))
+ except string.atoi_error:
+ objectName.append(subOid)
+ ctx['objectName'] = tuple(objectName)
+
+ def n_ObjectIndex(self, (snmpEngine, ctx), node):
+ if not ctx.has_key('objectIndices'):
+ ctx['objectIndices'] = []
+ ctx['objectIndices'].append(node[1].attr)
+
+ def n_VarName_exit(self, (snmpEngine, ctx), node):
+ mibViewCtl = ctx['mibViewController']
+ if ctx.has_key('modName'):
+ mibViewCtl.mibBuilder.loadModules(ctx['modName'])
+ if ctx.has_key('objectName'):
+ 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 filter(None, map(lambda x: type(x) not in
+ (types.LongType, types.IntType), suffix)):
+ 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 ctx.has_key('objectIndices'):
+ modName, nodeDesc, _suffix = mibViewCtl.getNodeLocation(
+ mibNode.name[:-1]
+ )
+ mibNode, = mibViewCtl.mibBuilder.importSymbols(
+ modName, nodeDesc
+ )
+ suffix = suffix + apply(
+ mibNode.getInstIdFromIndices, ctx['objectIndices']
+ )
+ else:
+ if ctx.has_key('objectIndices'):
+ raise error.PySnmpError(
+ 'Cant resolve indices: %s' % ctx['objectIndices']
+ )
+ ctx['varName'] = oid + suffix
+ if ctx.has_key('objectName'):
+ del ctx['objectName']
+ if ctx.has_key('objectIndices'):
+ del ctx['objectIndices']
+
+ def n_VarBind_exit(self, (snmpEngine, ctx), node):
+ if not ctx.has_key('varBinds'):
+ ctx['varBinds'] = [ (ctx['varName'], None) ]
+ else:
+ ctx['varBinds'].append((ctx['varName'], None))
+ del ctx['varName']
+
+ def n_VarBinds_exit(self, (mibViewProxy, ctx), node):
+ if not ctx.has_key('varBinds') or not ctx['varBinds']:
+ ctx['varBinds'] = [ ((1, 3, 6), None) ]
+
+def readPduGenerator((snmpEngine, ctx), ast):
+ __ReadPduGenerator().preorder((snmpEngine, ctx), 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, (snmpEngine, ctx), node):
+ ctx['varType'] = node[0].attr
+
+ def n_VarValue(self, (snmpEngine, ctx), node):
+ ctx['varValue'] = node[0].attr
+
+ def n_VarBind_exit(self, (snmpEngine, ctx), node):
+ mibViewCtl = ctx['mibViewController']
+ if ctx['varType'] == '=':
+ modName, nodeDesc, suffix = mibViewCtl.getNodeLocation(ctx['varName'])
+ mibNode, = mibViewCtl.mibBuilder.importSymbols(modName, nodeDesc)
+ if hasattr(mibNode, 'syntax'):
+ if suffix != (0,):
+ raise error.PySnmpError(
+ 'Found MIB scalar %s but non-scalar given %s' %
+ (mibNode.name + (0,), ctx['varName'])
+ )
+ else:
+ val = mibNode.syntax
+ else:
+ raise error.PySnmpError(
+ 'Variable %s has no syntax' % (ctx['varName'],)
+ )
+ else:
+ val = self._typeMap[ctx['varType']]
+ try:
+ val = val.clone(ctx['varValue'])
+ except PyAsn1Error, why:
+ raise error.PySnmpError(why)
+
+ if not ctx.has_key('varBinds'):
+ ctx['varBinds'] = [ (ctx['varName'], val) ]
+ else:
+ ctx['varBinds'].append((ctx['varName'], val))
+
+def writePduGenerator((snmpEngine, ctx), ast):
+ __WritePduGenerator().preorder((snmpEngine, ctx), ast)
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/secmod.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/secmod.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/secmod.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/secmod.py Fri May 5 06:11:08 2006
@@ -1,0 +1,250 @@
+import string
+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\"\n\
+ -X PRIV-KEY user privacy key\n\
+ -e CONTEXT-ENGINE-ID authoritative context engine ID\n\
+ -E CONTEXT-NAME authoritative context name\n\
+ -e ENGINE-ID authoritative SNMP engine ID (will discover)\n\
+ -Z ENGINE-BOOTS local SNMP engine uptime\n\
+"
+
+# Scanner
+
+class SMScannerMixIn:
+ # SNMPv1/v2
+
+ def t_community(self, s):
+ r' -c '
+ self.rv.append(base.ConfigToken('community'))
+
+ # SNMPv3
+
+ def t_authProtocol(self, s):
+ r' -a '
+ self.rv.append(base.ConfigToken('authProtocol'))
+
+ def t_authKey(self, s):
+ r' -A '
+ self.rv.append(base.ConfigToken('authKey'))
+
+ def t_privProtocol(self, s):
+ r' -x '
+ self.rv.append(base.ConfigToken('privProtocol'))
+
+ def t_privKey(self, s):
+ r' -X '
+ self.rv.append(base.ConfigToken('privKey'))
+
+ def t_securityName(self, s):
+ r' -u '
+ self.rv.append(base.ConfigToken('securityName'))
+
+ def t_securityLevel(self, s):
+ r' -l '
+ self.rv.append(base.ConfigToken('securityLevel'))
+
+ def t_engineID(self, s):
+ r' -e '
+ self.rv.append(base.ConfigToken('engineID'))
+
+ def t_contextEngineId(self, s):
+ r' -E '
+ self.rv.append(base.ConfigToken('contextEngineId'))
+
+ def t_contextName(self, s):
+ r' -n '
+ self.rv.append(base.ConfigToken('contextName'))
+
+ def t_engineBoots(self, s):
+ r' -Z '
+ self.rv.append(base.ConfigToken('engineBoots'))
+
+# Parser
+
+class SMParserMixIn:
+ def p_smSpec(self, args):
+ '''
+ Option ::= SnmpV1Option
+ Option ::= SnmpV3Option
+
+ SnmpV1Option ::= Community
+ Community ::= community string
+ Community ::= community whitespace string
+
+ SnmpV3Option ::= AuthProtocol
+ SnmpV3Option ::= AuthKey
+ SnmpV3Option ::= PrivProtocol
+ SnmpV3Option ::= PrivKey
+ SnmpV3Option ::= SecurityName
+ SnmpV3Option ::= SecurityLevel
+ SnmpV3Option ::= EngineID
+ SnmpV3Option ::= ContextEngineId
+ SnmpV3Option ::= ContextName
+ SnmpV3Option ::= EngineBoots
+
+ AuthProtocol ::= authProtocol string
+ AuthProtocol ::= authProtocol whitespace string
+ AuthKey ::= authKey string
+ AuthKey ::= authKey whitespace string
+ PrivProtocol ::= privProtocol string
+ PrivProtocol ::= privProtocol whitespace string
+ PrivKey ::= privKey string
+ PrivKey ::= privKey whitespace string
+ SecurityName ::= securityName string
+ SecurityName ::= securityName whitespace string
+ SecurityLevel ::= securityLevel string
+ SecurityLevel ::= securityLevel whitespace string
+ EngineID ::= engineID string
+ EngineID ::= engineID whitespace string
+ ContextEngineId ::= contextEngineId string
+ ContextEngineId ::= contextEngineId whitespace string
+ ContextName ::= contextName string
+ ContextName ::= contextName whitespace string
+ EngineBoots ::= engineBoots string
+ EngineBoots ::= engineBoots whitespace string
+ '''
+# Generator
+
+class __SMGenerator(base.GeneratorTemplate):
+ # SNMPv1/v2
+ def n_Community(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['communityName'] = node[2].attr
+ else:
+ ctx['communityName'] = node[1].attr
+
+ # SNMPv3
+ def n_AuthProtocol(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ p = string.upper(node[2].attr)
+ else:
+ p = string.upper(node[1].attr)
+ if string.find(p, 'MD5') != -1:
+ ctx['authProtocol'] = config.usmHMACMD5AuthProtocol
+ elif string.find(p, 'SHA') != -1:
+ ctx['authProtocol'] = config.usmHMACSHAAuthProtocol
+ else:
+ raise error.PySnmpError('Unknown auth protocol \"%s\"' % p)
+
+ def n_AuthKey(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['authKey'] = node[2].attr
+ else:
+ ctx['authKey'] = node[1].attr
+
+ def n_PrivProtocol(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ p = string.upper(node[2].attr)
+ else:
+ p = string.upper(node[1].attr)
+ if string.find(p, 'DES') != -1:
+ ctx['privProtocol'] = config.usmDESPrivProtocol
+ else:
+ raise error.PySnmpError('Unknown priv protocol \"%s\"' % p)
+
+ def n_PrivKey(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['privKey'] = node[2].attr
+ else:
+ ctx['privKey'] = node[1].attr
+
+ def n_SecurityName(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['securityName'] = node[2].attr
+ else:
+ ctx['securityName'] = node[1].attr
+
+ def n_SecurityLevel(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['securityLevel'] = node[2].attr
+ else:
+ ctx['securityLevel'] = node[1].attr
+
+ def n_EngineID(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['engineID'] = node[2].attr
+ else:
+ ctx['engineID'] = node[1].attr
+
+ def n_ContextEngineId(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['contextEngineId'] = node[2].attr
+ else:
+ ctx['contextEngineId'] = node[1].attr
+
+ def n_ContextName(self, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ ctx['contextName'] = node[2].attr
+ else:
+ ctx['contextName'] = node[1].attr
+
+ def n_EngineBoots(self, (snmpEngine, ctx), node): # XXX
+ if len(node) > 2:
+ ctx['engineBoots'] = node[2].attr
+ else:
+ ctx['engineBoots'] = node[1].attr
+
+def generator((snmpEngine, ctx), ast):
+ __SMGenerator().preorder((snmpEngine, ctx), ast)
+ # Commit collected data
+ if ctx['versionId'] == 3:
+ if not ctx.has_key('securityName'):
+ raise error.PySnmpError('Security name not specified')
+ if not ctx.has_key('securityLevel'):
+ raise error.PySnmpError('Security level not specified')
+ if ctx['securityLevel'] == 'noAuthNoPriv':
+ if ctx.has_key('authKey'): del ctx['authKey']
+ if ctx.has_key('privKey'): del ctx['privKey']
+ elif ctx['securityLevel'] == 'authNoPriv':
+ if ctx.has_key('privKey'): del ctx['privKey']
+ if ctx.has_key('authKey'):
+ if not ctx.has_key('authProtocol'):
+ ctx['authProtocol'] = config.usmHMACMD5AuthProtocol
+ else:
+ ctx['authProtocol'] = config.usmNoAuthProtocol
+ ctx['authKey'] = ''
+ if ctx.has_key('privKey'):
+ if not ctx.has_key('privProtocol'):
+ ctx['privProtocol'] = config.usmDESPrivProtocol
+ else:
+ ctx['privProtocol'] = config.usmNoPrivProtocol
+ ctx['privKey'] = ''
+ config.addV3User(
+ snmpEngine,
+ ctx['securityName'],
+ ctx['authProtocol'],
+ ctx['authKey'],
+ ctx['privProtocol'],
+ ctx['privKey']
+ )
+
+ else: # SNMPv1/v2c
+ if not ctx.has_key('communityName'):
+ 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']
+ )
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/spark.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/spark.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/spark.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/spark.py Fri May 5 06:11:08 2006
@@ -1,0 +1,569 @@
+# 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
+import string
+
+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 not namedict.has_key(name):
+ 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 string.join(rv, '|')
+
+ def error(self, s, pos):
+ print "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 self.index2func.has_key(i):
+ 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 = string.split(doc)
+
+ 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 self.rules.has_key(lhs):
+ 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 not self.first.has_key(lhs):
+ self.first[lhs] = {}
+
+ if len(rhs) == 0:
+ self.first[lhs][None] = 1
+ continue
+
+ sym = rhs[0]
+ if not self.rules.has_key(sym):
+ 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):
+ print "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 xrange(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 self.rules.has_key(nextSym):
+ #
+ # 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 needsCompletion.has_key(nextSym):
+ 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 predicted.has_key(nextSym):
+ 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 not self.rules.has_key(prhs0):
+ if prhs0 != ttype:
+ continue
+ else:
+ state.append(new)
+ continue
+ first = self.first[prhs0]
+ if not first.has_key(None) and \
+ not first.has_key(ttype):
+ 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 \
+ not self.rules.has_key(prhs[0]) 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 not tree.has_key(want):
+ #
+ # 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()
+ list = map(lambda (a,b): b, sortlist)
+ return children[name2index[self.resolve(list)]]
+
+ 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_<node type>, falling
+# back onto the default() method if the n_* can't be found. The preorder
+# traversal also looks for an exit hook named n_<node type>_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:
+ 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 string.join(rhs[:pos]),
+ print '.',
+ print string.join(rhs[pos:]),
+ print ',', parent, '.', pos
+# print ',', parent
+ if i < len(tokens):
+ print
+ print 'token', str(tokens[i])
+ print
Added: packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/target.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/target.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/target.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/pysnmp_apps/v4/cli/target.py Fri May 5 06:11:08 2006
@@ -1,0 +1,135 @@
+import string, socket
+from pysnmp_apps.cli import base
+from pysnmp.entity import config
+from pysnmp.carrier.asynsock.dgram import udp
+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\
+ [<transport-domain>:]<transport-endpoint>\n\
+ transport-domain: \"udp\"\n\
+ transport-endpoint: \"IP\"|\"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_dump(self, s):
+ r' -d '
+ self.rv.append(base.ConfigToken('dump'))
+
+# 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
+
+ DebugOption ::= Dump
+ Dump ::= dump
+
+ Agent ::= Transport semicolon Endpoint semicolon Format
+ Agent ::= Endpoint semicolon Format
+ Agent ::= Endpoint
+
+ Transport ::= string
+ Endpoint ::= string
+ Format ::= string
+ '''
+# Generator
+
+class __TargetGeneratorPassOne(base.GeneratorTemplate):
+ _snmpDomainMap = {
+ 'udp': (udp.snmpUDPDomain, udp.UdpSocketTransport(),
+ lambda h,p='161': (socket.gethostbyname(h), string.atoi(p)))
+ }
+ def n_Transport(self, (msgAndPduDsp, ctx), node):
+ if self._snmpDomainMap.has_key(node[0].attr):
+ ( 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, (msgAndPduDsp, ctx), node):
+ ctx['transportAddress'] = node[0].attr
+
+ def n_Format(self, (msgAndPduDsp, ctx), node):
+ ctx['transportFormat'] = node[0].attr
+
+ def n_Agent_exit(self, (msgAndPduDsp, ctx), node):
+ if ctx.has_key('transportFormat'):
+ ctx['transportAddress'] = (
+ ctx['transportAddress'], ctx['transportFormat']
+ )
+ del ctx['transportFormat']
+ else:
+ ctx['transportAddress'] = ( ctx['transportAddress'], )
+ if not ctx.has_key('transportDomain'):
+ ( ctx['transportDomain'],
+ ctx['transportModule'],
+ ctx['addrRewriteFun'] ) = self._snmpDomainMap['udp']
+
+class __TargetGeneratorPassTwo(base.GeneratorTemplate):
+ def n_Retries(self, (snmpEngine, ctx), node):
+ 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, (snmpEngine, ctx), node):
+ try:
+ if len(node) > 2:
+ ctx['timeout'] = int(node[2].attr)*1000
+ else:
+ ctx['timeout'] = int(node[1].attr)*1000
+ except:
+ raise error.PySnmpError('Bad timeout value')
+
+ def n_Agent_exit(self, (snmpEngine, ctx), node):
+ ctx['addrName'] = '%s-name' % ctx['paramsName']
+ config.addTargetAddr(
+ snmpEngine,
+ ctx['addrName'],
+ ctx['transportDomain'],
+ apply(ctx['addrRewriteFun'], ctx['transportAddress']),
+ ctx['paramsName'],
+ ctx.get('timeout'),
+ ctx.get('retryCount')
+ )
+ config.addSocketTransport(
+ snmpEngine,
+ ctx['transportDomain'],
+ ctx['transportModule'].openClientMode()
+ )
+
+def generator((snmpEngine, ctx), ast):
+ __TargetGeneratorPassTwo().preorder(
+ __TargetGeneratorPassOne().preorder((snmpEngine, ctx), ast), ast
+ )
Added: packages/python-pysnmp4-apps/branches/upstream/current/setup.py
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/setup.py?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/setup.py (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/setup.py Fri May 5 06:11:08 2006
@@ -1,0 +1,15 @@
+#!/usr/bin/env python
+
+from distutils.core import setup
+
+setup(name="pysnmp-apps",
+ version="0.2.3a",
+ description="PySNMP applications",
+ author="Ilya Etingof",
+ author_email="ilya at glas.net ",
+ url="http://sourceforge.net/projects/pysnmp/",
+ packages = [ 'pysnmp_apps', 'pysnmp_apps.v4',
+ 'pysnmp_apps.v4.cli' ],
+ scripts = [ 'tools/pysnmpget', 'tools/pysnmpset',
+ 'tools/pysnmpwalk', 'tools/pysnmpbulkwalk' ],
+ license="BSD")
Added: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk Fri May 5 06:11:08 2006
@@ -1,0 +1,139 @@
+#!/usr/bin/env python
+#
+# GETBULK command generator
+#
+# Copyright 1999-2005 by Ilya Etingof <ilya at glas.net>.
+#
+import string, sys
+from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base
+from pysnmp.entity import engine
+from pysnmp.entity.rfc3413 import cmdgen
+from pysnmp import error
+
+def getUsage():
+ return "Usage: %s [OPTIONS] <AGENT> <PARAMETERS>\n\
+%s%s%s%s\
+GETBULK options:\n\
+ -C BULKOPTS: set various application specific behaviours:\n\
+ -n<NUM> set non-repeaters to <NUM>\n\
+ -r<NUM> set max-repeaters to <NUM>\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, (snmpEngine, ctx), node):
+ if len(node) > 2:
+ opt = node[2].attr
+ else:
+ opt = node[1].attr
+ n = r = None
+ for c in map(None, opt):
+ if c == 'n':
+ p = n = []
+ elif c == 'r':
+ p = r = []
+ else:
+ p.append(c)
+ if n: ctx['nonRepeaters'] = string.atoi(string.join(n, ''))
+ if r: ctx['maxRepetitions'] = string.atoi(string.join(r, ''))
+
+def generator((snmpEngine, ctx), ast):
+ return __Generator().preorder((snmpEngine, ctx), ast)
+
+snmpEngine = engine.SnmpEngine()
+
+try:
+ # Parse c/l into AST
+ ast = Parser().parse(
+ Scanner().tokenize(string.join(sys.argv[1:], ' '))
+ )
+
+ ctx = {}
+
+ # Apply configuration to SNMP entity
+ main.generator((snmpEngine, ctx), ast)
+ msgmod.generator((snmpEngine, ctx), ast)
+ secmod.generator((snmpEngine, ctx), ast)
+ mibview.generator((snmpEngine, ctx), ast)
+ target.generator((snmpEngine, ctx), ast)
+ pdu.readPduGenerator((snmpEngine, ctx), ast)
+ generator((snmpEngine, ctx), ast)
+
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n%s' % (why, getUsage()))
+ sys.exit(-1)
+
+# Run SNMP engine
+
+def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
+ varBindTable, cbCtx):
+ if errorIndication:
+ sys.stderr.write('%s\n' % errorIndication)
+ return
+ if errorStatus:
+ sys.stderr.write('%s\n' % errorStatus.prettyOut(errorStatus))
+ return
+ for varBindRow in varBindTable:
+ for oid, val in varBindRow:
+ if val is None:
+ continue
+ sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal(
+ cbCtx['mibViewController'], oid, val
+ ))
+ for oid, val in varBindTable[-1]:
+ if val is not None:
+ break
+ else:
+ return # stop on end-of-table
+ return 1 # continue walking
+
+cmdgen.BulkCommandGenerator().sendReq(
+ snmpEngine, ctx['addrName'],
+ ctx.get('nonRepeaters', 0), ctx.get('maxRepetitions', 25),
+ ctx['varBinds'], cbFun, ctx
+ )
+
+try:
+ snmpEngine.transportDispatcher.runDispatcher()
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n' % why)
+ sys.exit(-1)
Propchange: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpbulkwalk
------------------------------------------------------------------------------
svn:executable =
Added: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget Fri May 5 06:11:08 2006
@@ -1,0 +1,91 @@
+#!/usr/bin/env python
+#
+# GET command generator
+#
+# Copyright 1999-2005 by Ilya Etingof <ilya at glas.net>.
+#
+import string, sys
+from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base
+from pysnmp.entity import engine
+from pysnmp.entity.rfc3413 import cmdgen
+from pysnmp import error
+
+def getUsage():
+ return "Usage: %s [OPTIONS] <AGENT> <PARAMETERS>\n\
+%s%s%s%s%s%s" % (
+ sys.argv[0],
+ main.getUsage(),
+ msgmod.getUsage(),
+ secmod.getUsage(),
+ mibview.getUsage(),
+ target.getUsage(),
+ pdu.getReadUsage()
+ )
+
+# Construct c/l interpreter for this app
+
+class Scanner(
+ msgmod.MPScannerMixIn,
+ secmod.SMScannerMixIn,
+ mibview.MibViewScannerMixIn,
+ target.TargetScannerMixIn,
+ pdu.ReadPduScannerMixIn,
+ main.MainScannerMixIn,
+ base.ScannerTemplate
+ ): pass
+
+class Parser(
+ msgmod.MPParserMixIn,
+ secmod.SMParserMixIn,
+ mibview.MibViewParserMixIn,
+ target.TargetParserMixIn,
+ pdu.ReadPduParserMixIn,
+ main.MainParserMixIn,
+ base.ParserTemplate
+ ): pass
+
+snmpEngine = engine.SnmpEngine()
+
+try:
+ # Parse c/l into AST
+ ast = Parser().parse(
+ Scanner().tokenize(string.join(sys.argv[1:], ' '))
+ )
+
+ ctx = {}
+
+ # Apply configuration to SNMP entity
+ main.generator((snmpEngine, ctx), ast)
+ msgmod.generator((snmpEngine, ctx), ast)
+ secmod.generator((snmpEngine, ctx), ast)
+ mibview.generator((snmpEngine, ctx), ast)
+ target.generator((snmpEngine, ctx), ast)
+ pdu.readPduGenerator((snmpEngine, ctx), ast)
+
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n%s' % (why, getUsage()))
+ sys.exit(-1)
+
+# Run SNMP engine
+
+def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
+ varBinds, cbCtx):
+ if errorIndication:
+ sys.stderr.write('%s\n' % errorIndication)
+ elif errorStatus:
+ sys.stderr.write('%s\n' % errorStatus.prettyOut(errorStatus))
+ else:
+ for oid, val in varBinds:
+ sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal(
+ cbCtx['mibViewController'], oid, val
+ ))
+
+cmdgen.GetCommandGenerator().sendReq(
+ snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx
+ )
+
+try:
+ snmpEngine.transportDispatcher.runDispatcher()
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n' % why)
+ sys.exit(-1)
Propchange: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpget
------------------------------------------------------------------------------
svn:executable =
Added: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset Fri May 5 06:11:08 2006
@@ -1,0 +1,91 @@
+#!/usr/bin/env python
+#
+# SET command generator
+#
+# Copyright 1999-2005 by Ilya Etingof <ilya at glas.net>.
+#
+import string, sys
+from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base
+from pysnmp.entity import engine
+from pysnmp.entity.rfc3413 import cmdgen
+from pysnmp import error
+
+def getUsage():
+ return "Usage: %s [OPTIONS] <AGENT> <PARAMETERS>\n\
+%s%s%s%s%s%s" % (
+ sys.argv[0],
+ main.getUsage(),
+ msgmod.getUsage(),
+ secmod.getUsage(),
+ mibview.getUsage(),
+ target.getUsage(),
+ pdu.getWriteUsage()
+ )
+
+# Construct c/l interpreter for this app
+
+class Scanner(
+ msgmod.MPScannerMixIn,
+ secmod.SMScannerMixIn,
+ mibview.MibViewScannerMixIn,
+ target.TargetScannerMixIn,
+ pdu.WritePduScannerMixIn,
+ main.MainScannerMixIn,
+ base.ScannerTemplate
+ ): pass
+
+class Parser(
+ msgmod.MPParserMixIn,
+ secmod.SMParserMixIn,
+ mibview.MibViewParserMixIn,
+ target.TargetParserMixIn,
+ pdu.WritePduParserMixIn,
+ main.MainParserMixIn,
+ base.ParserTemplate
+ ): pass
+
+snmpEngine = engine.SnmpEngine()
+
+try:
+ # Parse c/l into AST
+ ast = Parser().parse(
+ Scanner().tokenize(string.join(sys.argv[1:], ' '))
+ )
+
+ ctx = {}
+
+ # Apply configuration to SNMP entity
+ main.generator((snmpEngine, ctx), ast)
+ msgmod.generator((snmpEngine, ctx), ast)
+ secmod.generator((snmpEngine, ctx), ast)
+ mibview.generator((snmpEngine, ctx), ast)
+ target.generator((snmpEngine, ctx), ast)
+ pdu.writePduGenerator((snmpEngine, ctx), ast)
+
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n%s' % (why, getUsage()))
+ sys.exit(-1)
+
+# Run SNMP engine
+
+def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
+ varBinds, cbCtx):
+ if errorIndication:
+ sys.stderr.write('%s\n' % errorIndication)
+ elif errorStatus:
+ sys.stderr.write('%s\n' % errorStatus.prettyOut(errorStatus))
+ else:
+ for oid, val in varBinds:
+ sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal(
+ cbCtx['mibViewController'], oid, val
+ ))
+
+cmdgen.SetCommandGenerator().sendReq(
+ snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx
+ )
+
+try:
+ snmpEngine.transportDispatcher.runDispatcher()
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s' % why)
+ sys.exit(-1)
Propchange: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpset
------------------------------------------------------------------------------
svn:executable =
Added: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk
URL: http://svn.debian.org/wsvn/python-modules/packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk?rev=420&op=file
==============================================================================
--- packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk (added)
+++ packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk Fri May 5 06:11:08 2006
@@ -1,0 +1,101 @@
+#!/usr/bin/env python
+#
+# GETNEXT command generator
+#
+# Copyright 1999-2005 by Ilya Etingof <ilya at glas.net>.
+#
+import string, sys
+from pysnmp_apps.cli import main, msgmod, secmod, target, pdu, mibview, base
+from pysnmp.entity import engine
+from pysnmp.entity.rfc3413 import cmdgen
+from pysnmp import error
+
+def getUsage():
+ return "Usage: %s [OPTIONS] <AGENT> <PARAMETERS>\n\
+%s%s%s%s%s%s" % (
+ sys.argv[0],
+ main.getUsage(),
+ msgmod.getUsage(),
+ secmod.getUsage(),
+ mibview.getUsage(),
+ target.getUsage(),
+ pdu.getReadUsage()
+ )
+
+# Construct c/l interpreter for this app
+
+class Scanner(
+ msgmod.MPScannerMixIn,
+ secmod.SMScannerMixIn,
+ mibview.MibViewScannerMixIn,
+ target.TargetScannerMixIn,
+ pdu.ReadPduScannerMixIn,
+ main.MainScannerMixIn,
+ base.ScannerTemplate
+ ): pass
+
+class Parser(
+ msgmod.MPParserMixIn,
+ secmod.SMParserMixIn,
+ mibview.MibViewParserMixIn,
+ target.TargetParserMixIn,
+ pdu.ReadPduParserMixIn,
+ main.MainParserMixIn,
+ base.ParserTemplate
+ ): pass
+
+snmpEngine = engine.SnmpEngine()
+
+try:
+ # Parse c/l into AST
+ ast = Parser().parse(
+ Scanner().tokenize(string.join(sys.argv[1:], ' '))
+ )
+
+ ctx = {}
+
+ # Apply configuration to SNMP entity
+ main.generator((snmpEngine, ctx), ast)
+ msgmod.generator((snmpEngine, ctx), ast)
+ secmod.generator((snmpEngine, ctx), ast)
+ mibview.generator((snmpEngine, ctx), ast)
+ target.generator((snmpEngine, ctx), ast)
+ pdu.readPduGenerator((snmpEngine, ctx), ast)
+
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n%s' % (why, getUsage()))
+ sys.exit(-1)
+
+# Run SNMP engine
+
+def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
+ varBindTable, cbCtx):
+ if errorIndication:
+ sys.stderr.write('%s\n' % errorIndication)
+ return
+ if errorStatus:
+ sys.stderr.write('%s\n' % errorStatus.prettyOut(errorStatus))
+ return
+ for varBindRow in varBindTable:
+ for oid, val in varBindRow:
+ if val is None:
+ continue
+ sys.stdout.write('%s\n' % cbCtx['mibViewProxy'].getPrettyOidVal(
+ cbCtx['mibViewController'], oid, val
+ ))
+ for oid, val in varBindTable[-1]:
+ if val is not None:
+ break
+ else:
+ return # stop on end-of-table
+ return 1 # continue walkin
+
+cmdgen.NextCommandGenerator().sendReq(
+ snmpEngine, ctx['addrName'], ctx['varBinds'], cbFun, ctx
+ )
+
+try:
+ snmpEngine.transportDispatcher.runDispatcher()
+except error.PySnmpError, why:
+ sys.stderr.write('Error: %s\n' % why)
+ sys.exit(-1)
Propchange: packages/python-pysnmp4-apps/branches/upstream/current/tools/pysnmpwalk
------------------------------------------------------------------------------
svn:executable =
More information about the Python-modules-commits
mailing list