Giter VIP home page Giter VIP logo

pysnmp's Introduction

SNMP library for Python

PyPI Python Versions GitHub license Build status Downloads

This is a pure-Python, open source and free implementation of v1/v2c/v3 SNMP engine distributed under 2-clause BSD license.

The PySNMP project was initially sponsored by a PSF grant. Thank you!

Features

  • Complete SNMPv1/v2c and SNMPv3 support
  • SMI framework for resolving MIB information and implementing SMI Managed Objects
  • Complete SNMP entity implementation
  • USM Extended Security Options support (3DES, 192/256-bit AES encryption)
  • Extensible network transports framework (UDP/IPv4, UDP/IPv6)
  • Asynchronous socket-based IO API support
  • Twisted, Asyncio and Trollius integration
  • PySMI integration for dynamic MIB compilation
  • Built-in instrumentation exposing protocol engine operations
  • Python eggs and py2exe friendly
  • 100% Python, works with Python 2.6 though 3.7
  • MT-safe (if SnmpEngine is thread-local)

Features, specific to SNMPv3 model include:

  • USM authentication (MD5/SHA-1/SHA-2) and privacy (DES/AES) protocols (RFC3414, RFC7860)
  • View-based access control to use with any SNMP model (RFC3415)
  • Built-in SNMP proxy PDU converter for building multi-lingual SNMP entities (RFC2576)
  • Remote SNMP engine configuration
  • Optional SNMP engine discovery
  • Shipped with standard SNMP applications (RC3413)

Download & Install

The PySNMP software is freely available for download from PyPI and GitHub.

Just run:

$ pip install pysnmp

to download and install PySNMP along with its dependencies:

  • PyASN1
  • PySMI (required for MIB services only)
  • Optional pysnmpcrypto package whenever strong SNMPv3 encryption is desired

Besides the library, command-line SNMP utilities written in pure-Python could be installed via:

$ pip install snmpclitools

and used in the very similar manner as conventional Net-SNMP tools:

$ snmpget.py -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 demo.snmplabs.com sysDescr.0
SNMPv2-MIB::sysDescr.0 = STRING: Linux zeus 4.8.6.5-smp #2 SMP Sun Nov 13 14:58:11 CDT 2016 i686

Examples

PySNMP is designed in a layered fashion. Top-level and easiest to use API is known as hlapi. Here's a quick example on how to SNMP GET:

from pysnmp.hlapi import *

iterator = getCmd(SnmpEngine(),
                  CommunityData('public'),
                  UdpTransportTarget(('demo.snmplabs.com', 161)),
                  ContextData(),
                  ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:  # SNMP engine errors
    print(errorIndication)
else:
    if errorStatus:  # SNMP agent errors
        print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
    else:
        for varBind in varBinds:  # SNMP response contents
            print(' = '.join([x.prettyPrint() for x in varBind]))

This is how to send SNMP TRAP:

from pysnmp.hlapi import *

errorIndication, errorStatus, errorIndex, varBinds = next(
    sendNotification(
        SnmpEngine(OctetString(hexValue='8000000001020304')),
        UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1',
                    authProtocol=USM_AUTH_HMAC96_SHA,
                    privProtocol=USM_PRIV_CFB128_AES),
        UdpTransportTarget(('demo.snmplabs.com', 162)),
        ContextData(),
        'trap',
        NotificationType(ObjectIdentity('SNMPv2-MIB', 'authenticationFailure'))
    )
)

if errorIndication:
    print(errorIndication)

We maintain publicly available SNMP Agent and TRAP sink at demo.snmplabs.com. You are welcome to use it while experimenting with whatever SNMP software you deal with.

$ python3 examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py
SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
$
$ python3 examples//hlapi/asyncore/sync/agent/ntforg/v3-inform.py
SNMPv2-MIB::sysUpTime.0 = 0
SNMPv2-MIB::snmpTrapOID.0 = SNMPv2-MIB::warmStart
SNMPv2-MIB::sysName.0 = system name

Other than that, PySNMP is capable to automatically fetch and use required MIBs from HTTP, FTP sites or local directories. You could configure any MIB source available to you (including this one) for that purpose.

For more example scripts please refer to examples section at pysnmp web site.

Documentation

Library documentation and examples can be found at the pysnmp project site.

If something does not work as expected, please open an issue at GitHub or post your question on Stack Overflow or try browsing pysnmp mailing list archives.

Bug reports and PRs are appreciated! ;-)

Copyright (c) 2005-2019, Ilya Etingof. All rights reserved.

pysnmp's People

Contributors

acspike avatar astralblue avatar cclauss avatar drrbreese avatar ericwb avatar etingof avatar fabriziovanni avatar gerrat avatar jcabmora avatar johnthagen avatar keuko avatar mattsb42-aws avatar mcfletch avatar primeos avatar roguelazer avatar rwallen avatar ryban avatar verrio avatar vincentbernat avatar wallies avatar yegorich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pysnmp's Issues

pysnmp.smi.error.SmiError: MIB object ObjectIdentity('1.3.6.1.4.1.9.9.96.1.1.1.1.2.100') is not OBJECT-TYPE (MIB not loaded?)

I am attempting to use an SNMP set command to copy config files on a Cisco device.

I am attempting to use the OID for Cisco Config Copy MIB.

The first OID is 1.3.6.1.4.1.9.9.96.1.1.1.1.2.x.

I simply cannot get it to work.

from pysnmp.hlapi import *

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in setCmd(SnmpEngine(),
                          CommunityData('private'),
                          UdpTransportTarget(('10.18.15.120', 161)),
                          ContextData(),
                          ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.96.1.1.1.1.2.100'), 2),
                          lookupMib=False):

    if errorIndication:
        print(errorIndication)
        break
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

Traceback (most recent call last):
File "C:\Project Files\snmptest.py", line 11, in
lookupMib=False):
File "C:\Python27\lib\site-packages\pysnmp\hlapi\asyncore\sync\cmdgen.py", line 210, in setCmd
lookupMib=options.get('lookupMib', True)))
File "C:\Python27\lib\site-packages\pysnmp\hlapi\asyncore\cmdgen.py", line 235, in setCmd
contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds),
File "C:\Python27\lib\site-packages\pysnmp\hlapi\varbinds.py", line 36, in makeVarBinds
__varBinds.append(varBind.resolveWithMib(mibViewController))
File "C:\Python27\lib\site-packages\pysnmp\smi\rfc1902.py", line 845, in resolveWithMib
raise SmiError('MIB object %r is not OBJECT-TYPE (MIB not loaded?)' % (self.__args[0],))
pysnmp.smi.error.SmiError: MIB object ObjectIdentity('1.3.6.1.4.1.9.9.96.1.1.1.1.2.100') is not OBJECT-TYPE (MIB not loa
ded?)

If I'm using OID why do I need an MIB? Why does it not have this MIB anyways if its on http://mibs.snmplabs.com/asn1/CISCO-CONFIG-COPY-MIB, and how do I fix?

PySNMP needs to pin to a single version of PyASN1

Twice in the past month PyASN1 has had a release (0.2.2 and 0.2.3) that has broken PySNMP prior to the latest version. This would not be a problem if the previous versions of PySNMP were compatible with PyASN1. However it seems that the changes to PyASN1 break backwards compatibility even though only the micro version number is incremented.

I believe that PySNMP should be pinned to a single compatible version of PyASN1 to prevent this issue in the future.

Compare snimpy

What's the differentce between pysnmp and (snimpy)[https://github.com/vincentbernat/snimpy]

  • disadvantages
  • advantages

SNMPV3 3DES privacy does not work.

SNMPV3 3DES privacy does not work. This is because the key localization done in the
current version follows https://tools.ietf.org/html/draft-blumenthal-aes-usm-04 which
is for AES only. Key localization should be done as per https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00
Also, the current encrypt/decrypt methods are doing extra, unnecessary work.
All they need to do is use the encrypt/decrypt methods provided by the 3DES object from Pycrypto.

Please see the pull request that fixes this issue.

asyncio "Task was destroyed but it is pending!" in pysnmp sample program

I am testing pysnmp asyncio module and as the start used the sample program provided along with the documentation. When I run the sample program, it gives the Task was destroyed but it is pending! error. I checked SO for similar questions and could not find what is wrong with my (inexperienced) eyes. I am using Python 3.4.2 and asyncio that came with it and pysnmp (4.3.2) on Debian 8.5

The program I using (the same as the sample program in pysnmp documentation)

 
    import asyncio
    from pysnmp.hlapi.asyncio import *
    
    
    @asyncio.coroutine
    def getone(snmpEngine, hostname):
        errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
            snmpEngine,
            CommunityData('public'),
            UdpTransportTarget(hostname),
            ContextData(),
            ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
        )
    
        if errorIndication:
            print(errorIndication)
        elif errorStatus:
            print('%s at %s' % (
                errorStatus.prettyPrint(),
                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
            )
                  )
        else:
            for varBind in varBinds:
                print(' = '.join([x.prettyPrint() for x in varBind]))
    
    
    @asyncio.coroutine
    def getall(snmpEngine, hostnames):
        for hostname in hostnames:
            yield from getone(snmpEngine, hostname)
    
    
    snmpEngine = SnmpEngine()
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(getall(snmpEngine, [('demo.snmplabs.com', 1161),
                                                ('demo.snmplabs.com', 2161),
                                                ('demo.snmplabs.com', 3161)]))
  

Error is:

 

     Executing  wait_for= cb=[_raise_stop_error() at /usr/lib/python3.4/asyncio/base_event
    s.py:101] created at /usr/lib/python3.4/asyncio/base_events.py:264> took 0.460 seconds
    SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
    SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
    SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m
    Task was destroyed but it is pending!
    source_traceback: Object created at (most recent call last):
      File "multiple-sequential-queries.py", line 58, in 
        ('demo.snmplabs.com', 3161)]))   
      File "/usr/lib/python3.4/asyncio/base_events.py", line 271, in run_until_complete
        self.run_forever()
      File "/usr/lib/python3.4/asyncio/base_events.py", line 244, in run_forever
        self._run_once()
      File "/usr/lib/python3.4/asyncio/base_events.py", line 1075, in _run_once
        handle._run()
      File "/usr/lib/python3.4/asyncio/events.py", line 120, in _run
        self._callback(*self._args)
      File "/usr/lib/python3.4/asyncio/tasks.py", line 237, in _step
        result = next(coro)
      File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__
        return next(self.gen)
      File "multiple-sequential-queries.py", line 50, in getall
        yield from getone(snmpEngine, hostname)
      File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__
        return next(self.gen)
      File "multiple-sequential-queries.py", line 31, in getone
        ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
      File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__
        return next(self.gen)
      File "/usr/lib/python3.4/asyncio/coroutines.py", line 141, in coro
        res = func(*args, **kw)
      File "/usr/local/lib/python3.4/dist-packages/pysnmp/hlapi/asyncio/cmdgen.py", line 138, in getCmd
        addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget)
      File "/usr/local/lib/python3.4/dist-packages/pysnmp/hlapi/lcd.py", line 87, in configure
        transport
      File "/usr/local/lib/python3.4/dist-packages/pysnmp/entity/config.py", line 308, in addTransport
        transport)
      File "/usr/local/lib/python3.4/dist-packages/pysnmp/carrier/asyncio/dispatch.py", line 70, in registerTransport
        self.loopingcall = asyncio.async(self.handle_timeout())
    task: :4> wait_for= created at /usr/local/lib/python3.4/dist-packages/pysnmp/carrier/asyncio/dispatch.py:70>

 

Any help to figure this out is much appreciated!

Thanks.

SNMPV3 AES192/256 privacy does not work with Cisco IOS.

Pysnmp SNMPV3 AES192/AES256 privacy options does not work for Cisco devices
(test this with any Cisco device running an IOS that suppports AES192/AES256).

This is because Cisco devices (ie, IOS that supports AES192/AES256) do not use
https://tools.ietf.org/html/draft-blumenthal-aes-usm-04 for key localization/short key extension.
Instead, they use the procedure for 3DES key localization specified in
https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00 which
specifies the 3DES key localization/short key extension.
I believe Cisco did this because they view the reeder mechanism as an improvement
over the bluementhal mechanism.

Please see the pull request that fixes this issue. However, the pull breaks
SNMPV3 AES192/AES256 privacy for any device that uses the key localization in
https://tools.ietf.org/html/draft-blumenthal-aes-usm-04

MiB Translation Fail with resolveWithMib

Hi,

I am performing a walk(Refer walk_out.txt
walk_out.txt
) and then trying to translate the O/P using some thing like this:

        custom_mib_paths = "/data/users/MIBS/,/usr/share/snmp/mibs/"
        load_mib_modules = "SNMPv2-SMI,<CUSTOM-MIB-1>,<CUSTOM-MIB-2>"
        try:
            mibBuilder = builder.MibBuilder()
            compiler.addMibCompiler(mibBuilder, sources=custom_mib_paths)
            mibViewController = view.MibViewController(mibBuilder)
            for mibs in load_mib_modules.split(','):
                mibBuilder.loadModules(mibs)
        except error.MibNotFoundError:
            testcase_Utils.pNote("Mib Not Found!", "Error")
        output = rfc1902.ObjectType(rfc1902.ObjectIdentity(name), val).resolveWithMib(mibViewController).prettyPrint()

And getting this bellow error:

    output = rfc1902.ObjectType(rfc1902.ObjectIdentity(name), val).resolveWithMib(mibViewController).prettyPrint()
  File "/home/VIRT/lib/python2.7/site-packages/pysnmp/smi/rfc1902.py", line 853, in resolveWithMib
    raise SmiError('MIB object %r is not OBJECT-TYPE (MIB not loaded?)' % (self.__args[0],))
SmiError: MIB object ObjectIdentity(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.2.0'))) is not OBJECT-TYPE (MIB not loaded?)

Now without MIB Translation code (with prettyPrint ) its provides o/p something like this:

-I- SNMPv2-MIB::sysDescr.0 = Tseries
-I- SNMPv2-MIB::sysObjectID.0 = SNMPv2-SMI::enterprises.211.24.12
-I- SNMPv2-MIB::sysUpTime.0 = 677417

Now What could be the problem here with this Translation. Is it the custom MIB file which I am using is creatiing any problem ?
But '1.3.6.1.2.1.1.2.0' is a part of SNMPv2-SMI.

Problems forming instance-identifier for TCP-MIB::tcpConnectionState

Hello,

I am getting a different Instance identifier for TCP-MIB::tcpConnectionState than the one in the documentation (http://pysnmp.sourceforge.net/docs/pysnmp-hlapi-tutorial.html). I wonder if this is a problem with my local MIB or maybe a library problem.

from pysnmp.hlapi import ObjectIdentity
from pysnmp.smi import builder, view
mibBuilder = builder.MibBuilder()
mibViewController = view.MibViewController(mibBuilder)
x = ObjectIdentity('TCP-MIB', 'tcpConnectionState','ipv4', '195.218.254.105', 41511,'ipv4', '194.67.1.250', 993)
x.resolveWithMib(mibViewController)

After running x.getOid(), I get:

1.3.6.1.2.1.6.19.1.7.1.15.49.57.53.46.50.49.56.46.50.53.52.46.49.48.53.41511.1.12.49.57.52.46.54.55.46.49.46.50.53.48.993

To create the instances, Pysnmp is taking the IPs as variable-length strings instead of IPv4. The resulting OIDs will not function against a device, and I am not sure how to handle these situations.

I apologise if this is not a bug, but I got zero responses after posting this in the user list.

Could Not able To load "IF-MIB" using loadModules

Hi

I am having problem to load "IF-MIB" using loadModules.
Using PYSNMP-4.3.8.

after I call mibBuilder.loadModules('IF-MIB') its just hangs there.
Debug log attached.
Reproducible: Yes.
snmp_debug_log.txt

>>> from pysnmp.smi import builder, view, compiler, rfc1902, error
>>> custom_mib_paths = "/usr/share/snmp/mibs/"
>>> mibBuilder = builder.MibBuilder()
>>> compiler.addMibCompiler(mibBuilder, sources=custom_mib_paths)
>>> from pysnmp import debug
>>> debug.setLogger(debug.Debug('all'))
2017-07-05 09:06:01,505 pysnmp: running pysnmp version 4.3.8
2017-07-05 09:06:01,506 pysnmp: debug category 'all' enabled
>>> mibViewController = view.MibViewController(mibBuilder)
>>> mibBuilder.loadModules('IF-MIB')

Missing '

inside the example code there is a missing '
[https://github.com/etingof/pysnmp/blob/master/README.md]

at the line:
if errorStatus: # SNMP agent errors print(##here##%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))

thank you

Error installing on docker container

Hi,

I'm getting an error of file not found when attempted to install this library on my docker container.
can someone give me some advice on how to fix this?

pip install easysnmp
Collecting easysnmp
  Downloading easysnmp-0.2.4.tar.gz
Building wheels for collected packages: easysnmp
  Running setup.py bdist_wheel for easysnmp: started
  Running setup.py bdist_wheel for easysnmp: finished with status 'error'
  Complete output from command /usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-jO26Xl/easysnmp/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpSHS6Jfpip-wheel- --python-tag cp27:
  sh: 1: net-snmp-config: not found
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-2.7
  creating build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/easy.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/session.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/helpers.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/utils.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/__init__.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/variables.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/compat.py -> build/lib.linux-x86_64-2.7/easysnmp
  copying easysnmp/exceptions.py -> build/lib.linux-x86_64-2.7/easysnmp
  running build_ext
  building 'easysnmp.interface' extension
  creating build/temp.linux-x86_64-2.7
  creating build/temp.linux-x86_64-2.7/easysnmp
  gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.7 -c easysnmp/interface.c -o build/temp.linux-x86_64-2.7/easysnmp/interface.o -Wno-unused-function
  easysnmp/interface.c:3:38: fatal error: net-snmp/net-snmp-config.h: No such file or directory
   #include <net-snmp/net-snmp-config.h>
                                        ^
  compilation terminated.
  error: command 'gcc' failed with exit status 1

Thanks

Twisted hlapi: MIB resolution SmiError not handled

Some exceptions from the callback functions __cbFun are not handled.

Here is an exception happening during a MIB lookup with a value that does not satisfy a constraint.

Unhandled Error
Traceback (most recent call last):
  File "main.py", line 52, in <module>
    reactor.run()
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/twisted/internet/base.py", line 1194, in run
    self.mainLoop()
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/twisted/internet/base.py", line 1203, in mainLoop
    self.runUntilCurrent()
--- <exception caught here> ---
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/twisted/internet/base.py", line 825, in runUntilCurrent
    call.func(*call.args, **call.kw)
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/carrier/base.py", line 68, in _cbFun
    self, transportDomain, transportAddress, incomingMessage
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/entity/engine.py", line 145, in __receiveMessageCbFun
    self, transportDomain, transportAddress, wholeMsg
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/proto/rfc3412.py", line 458, in receiveMessage
    cachedParams['cbCtx'])
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/entity/rfc3413/cmdgen.py", line 131, in processResponsePdu
    cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/entity/rfc3413/cmdgen.py", line 355, in processResponseVarBinds
    varBindTable, cbCtx):
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/hlapi/twisted/cmdgen.py", line 477, in __cbFun
    [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable])
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/hlapi/varbinds.py", line 43, in unmakeVarBinds
    varBinds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]
  File "/home/nrolans/.venvs/blah/lib/python2.7/site-packages/pysnmp/smi/rfc1902.py", line 859, in resolveWithMib
    raise SmiError('MIB object %r having type %r failed to cast value %r: %s' % (self.__args[0].prettyPrint(), self.__args[0].getMibNode().getSyntax().__class__.__name__, self.__args[1], sys.exc_info()[1]))
pysnmp.smi.error.SmiError: MIB object 'BGP4-MIB::bgp4PathAttrASPathSegment.10.2.3.0.24.10.20.20.20' having type 'OctetString' failed to cast value OctetString(''): ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueSizeConstraint(0, 65535)), ValueSizeConstraint(2, 255)) failed at: "ValueSizeConstraint(2, 255) failed at: """ at OctetString

I currently work around this by catching all exceptions in __cbFun and calling the error callback like this.

    def __cbFun(snmpEngine, sendRequestHandle,
                errorIndication, errorStatus, errorIndex,
                varBindTable, cbCtx):
        try:
            lookupMib, deferred = cbCtx
            if errorIndication:
                deferred.errback(Failure(errorIndication))
            else:
                    deferred.callback(
                        (errorStatus, errorIndex,
                            [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable])
                    )
        except Exception as e:
            deferred.errback(Failure(e))

I'm happy to send a pull request with this or try another approach if you can give some direction.

I'm running Python 2.7.8 and these module versions

Twisted==16.2.0
pyasn1==0.1.9
pycrypto==2.6.1
pysmi==0.0.7
pysnmp==4.3.2

Thanks!

twisted: errors that are old-style classes do not work with Failure in callbacks

Hi!

  • Python 2.7.12
  • pysnmp (4.3.2)
  • Twisted (16.4.1)

First, Thanks for all your excellent work on pySNMP 👍

There seems to be a problem with running pySNMP with Twisted with respect to catching exceptions.

On this line pysnmp/hlapi/twisted/cmdgen.py:468, the code looks like this:

    def __cbFun(snmpEngine, sendRequestHandle,
                errorIndication, errorStatus, errorIndex,
                varBindTable, cbCtx):
        lookupMib, deferred = cbCtx
        if errorIndication:
            deferred.errback(Failure(errorIndication))   # <<===  Here
        else:
            deferred.callback(
                (errorStatus, errorIndex,
                 [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable])
            )

At the section marked, imagine that the errorIndication is a requestTimedOut error. If we now jump to pysnmp/proto/errind.py:70, we see where that object is defined:

class RequestTimedOut(ErrorIndication):
    pass

requestTimedOut = RequestTimedOut('No SNMP response received before timeout')

The RequestTimedOut class inherits from ErrorIndication which is created at the top of errind.py:

class ErrorIndication:
    """SNMPv3 error-indication values"""
    def __init__(self, descr=None):
        self.__value = self.__descr = self.__class__.__name__[0].lower() + self.__class__.__name__[1:]
        if descr:
            self.__descr = descr

    <snip>

So ErrorIndication is an old-style class. The problem with this is that the twisted errback system won't work with old-style classes. In my outer error handlers, the Failure value is given as a TypeError, not RequestTimedOut:

exceptions.TypeError: exceptions must be classes, or instances, not type

I have experimented with monkeypatching errind.py using this code in my main module:

# Monkeypatch pysnmp
import pysnmp.proto.errind as errind

class RequestTimedOut(Exception):
    pass

errind.RequestTimedOut = RequestTimedOut
errind.requestTimedOut = RequestTimedOut(
    'No SNMP response received before timeout'
)

<main function follows>

This appears to resolve the problem, and I am able to catch RequestTimedOut as a normal exception in my calling code.

The twisted documentation for the Failure class is linked here:

https://twistedmatrix.com/documents/current/api/twisted.python.failure.Failure.html#__init__

It mentions that it wants an Exception instance (or descendant we presume) to be passed to the Failure constructor, which is of course not what is currently being passed.

My proposal would be to make the ErrorIndication class (in errind.py) a new-style class by inheriting from Exception, but I am completely new to the pysnmp code base, and I don't know what that would break.

It is possible that I have missed some important detail, and if so, I apologise for wasting your time! Thanks again for all your work on pySNMP!

Slow encoding/decoding by comparison with libsnmp

We have a set of bespoke applications for polling thousands of devices in parallel, using Twisted and the old/unmaintained libsnmp.

We recently looked at porting this to Python 3 and moving to pysnmp, but performance was not acceptable for our needs. Pretty much all the time seems to be spent in encoding/decoding when I inspect using profile.

https://gist.github.com/philmayers/67b9300d8fb7282481a1a6af5ed45818

I'll attach The above gist is an example script which just decodes the same fake SNMPv2c PDU in a tight loop, measuring with timeit. Example results I get on my desktop under CPython:

timeit for libsnmp 10000 iterations per-call 0.336565ms
timeit for pysnmp 10000 iterations per-call 1.943247ms

I see similar differences under pypy although both times are obviously much better:

timeit for libsnmp 10000 iterations per-call 0.091585ms
timeit for pysnmp 10000 iterations per-call 0.306807ms

Under pypy with larger iterations, libsnmp improves dramatically (~3x faster) whereas pysnmp far less so (1.5x faster):

timeit for libsnmp 100000 iterations per-call 0.027657ms
timeit for pysnmp 100000 iterations per-call 0.200674ms

I suspect the performance difference here is coming from libsnmp having a much more primitive asn1 implementation and from it being far more monolithic - fewer function calls, less flexibility - and as such it's doing a lot less work, and is also easier for pypy to performance-hotspot.

For the time being, we'll probably fork libsnmp and try moving that to Python 3, or remain on 2.7 with libsnmp, but I thought this info might be of interest.

Many thanks for your hard work on pysnmp!

asyncio backend binds to an event loop at import time

The asyncio backend binds to a particular event loop at import time (see, for example, https://github.com/etingof/pysnmp/blob/master/pysnmp/carrier/asyncio/dgram/base.py#L44).

This causes it to not work (and occasionally do something very bad like write to the wrong socket) if multiple event loops are in-use.

I'm going to send up a PR which changes it to bind to an event loop at Carrier instantiation time, which is strictly better. Ideally, there should be a way to pass through a loop explicitly in the Transport constructor, but that's rather more of an API change.

How to disconnect SNMP notification reciever UDP port

I'm building a trap receiver based on this example: http://pysnmp.sourceforge.net/examples/current/v3arch/manager/ntfrcv/v3-multiple-users.html

I'm unable to get it to release the UDP port without exiting the application, which makes it difficult to start and stop in the setup and teardown of my tests.

If I run a watch -n 1 'netstat -ulpn | grep 162' as the tests run, I can see the port remains bound until the application exits, meaning that after multiple tests I have multiple servers bound to that port.

This is my current teardown code:

    ...
    self.snmpEngine.transportDispatcher.jobFinished(1)
    self.snmpEngine.transportDispatcher.unregisterRecvCbFun(recvId=None)
    self.snmpEngine.transportDispatcher.unregisterTransport(udp.domainName)
    self.snmpEngine.transportDispatcher.closeDispatcher()
    self.snmpEngine.unregisterTransportDispatcher(self.snmpEngine.transportDispatcher)

I'm basically calling every method that looks like it might do it, because I don't know what I'm doing :)

What am I missing to make it release the UDP port?

lexicographicMode seems to behave in an opposite manner.

Excellent work on the project!

Was trying to retrieve all variables per MIB and realized that running nextCmd with the option lexicographicMode unset (defaults to True according to the docs) yields beyond the scope of the MIB. Tried to explicitly set it to False and now it does not go beyond the scope of the MIB.

from pysnmp import hlapi as snmp

iterator = snmp.nextCmd(
    snmp.SnmpEngine(),
    snmp.CommunityData('public'),
    snmp.UdpTransportTarget(('192.168.1.11', 161)),
    snmp.ContextData(),
    snmp.ObjectType(snmp.ObjectIdentity('IF-MIB')),
    lexicographicMode=False,  # After setting this to False, it now seems return only the IF-MIB OIDs.
)

for errorIndication, errorStatus, errorIndex, varBinds in iterator:
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        print('=' * 80)
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

Or was I missing something?


I'm running on:
python:3.6 (docker)
pysnmp==4.3.5
pysmi==0.1.0
pysnmp-mibs==0.1.6

Memory leak using AsynCommandGenerator in pysnmp 4.3.2

We are using v4.3.2 and we are seeing the memory steadily increase when using AsynCommandGenerator. The code is like what is shown below. This is a SNMPGet class that we create and run for each set of OIDs we have. If we have a long running process that does this over and over, that process eventually consumes all the machine memory. We are using the memory_profiler library and @Profile decorator as described here: https://pypi.python.org/pypi/memory_profiler

Are we using AsynCommandGenerator incorrectly? How can we make the error growth go away in a long running process?

#
# worker class for snmp information
#
import threading
import sys

from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902
from memory_profiler import profile

class SNMPGet(object):
    def __init__(self, device_id, ip_address, object_identifiers, cookie, callback, error_callback):
        self.device_id = device_id
        self.ip_address = ip_address
        self.object_identifiers = object_identifiers
        self.cookie = cookie
        self.callback = callback
        self.error_callback = error_callback
        self.error_count = 0
        self.lock = threading.Lock()
        self.executing = False
        #
        self.cmd_gen=None
        self.targets=None

    def execute(self):
        if not self.executing:
            # Prevent lots of executions from accruing when errors occur
            self.executing = True
            for tmp_object_identifiers in self.object_identifiers:
                self._internal_execute(tmp_object_identifiers)
            self.executing = False

    @profile
    def _internal_execute(self, tmp_object_identifiers):
        try:
            try:
                del self.cmd_gen
            except:
                pass
            try:
                del self.targets
            except:
                pass

            self.cmd_gen = cmdgen.AsynCommandGenerator()

            self.targets = (
                (cmdgen.CommunityData('public', mpModel=0),
                 cmdgen.UdpTransportTarget((self.ip_address, 161), retries=0),
                 tmp_object_identifiers),)

            for auth_data, transport_target, var_names in self.targets:
                res = self.cmd_gen.getCmd(auth_data, transport_target, var_names, (self._snmp_callback, None))
                del res

            self.cmd_gen.snmpEngine.transportDispatcher.runDispatcher()

        except Exception as exc:
            sys.stderr.write('%s\n' % (exc,))
            self._increment_error_count()
            self.error_callback(self, self.cookie)
        finally:
            try:
                self.cmd_gen.uncfgCmdGen()
            except:
                pass
            try:
                del self.cmd_gen
            except:
                pass
            try:
                del self.targets 
            except:
                pass

    def _snmp_callback(self, send_request_handle, error_indication, error_status, error_index, var_binds, cbCtx):
        if error_indication:
            self._increment_error_count()
            self.error_callback(self, self.cookie)
            return

        if error_status:
            self._increment_error_count()
            self.error_callback(self, self.cookie)
            return

        self.callback(self, var_binds, self.cookie)
        self.reset_error_count()

    def _increment_error_count(self):
        self.lock.acquire()
        try:
            self.error_count += 1
        finally:
            self.lock.release()

    def reset_error_count(self):
        self.lock.acquire()
        try:
            self.error_count = 0
        finally:
            self.lock.release()

TRAP Reciver in PYSNMP 4.3.4 ;RuntimeError: maximum recursion depth exceeded while calling a Python object

The Pysnmp Trap Reciver is crashing with PYSNMP-4.3.4 same with 4.3.3 With 4.3.2 it was working just fine.
with error:
;RuntimeError: maximum recursion depth exceeded while calling a Python object

Iusse is reproducable every time when there is multiple trap message sent from the agent.
Meaning with:
snmptrap -v3 -u user_auth1 -l noAuthNoPriv -e 80000F150000000000000000 127.0.0.1:1036 123 1.3.6.1.6.3.1.1.5.1
Trap message recive and decode happnes just fine.

Test Platform: Red Hat Enterprise Linux Server release 6.8
Python: 2.7.8
PIP LIST:
pip.txt

Refer error.txt for the error details.
error.txt

for used code please refer:
trap_.txt

Filtering not working?

Hi according to documentation following should be equivalent with the appended snmpwalk:

from pysnmp.hlapi import *

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in nextCmd(SnmpEngine(),
                          UsmUserData('usr-md5-none', 'authkey1'),
                          UdpTransportTarget(('demo.snmplabs.com', 161)),
                          ContextData(),
                          ObjectType(ObjectIdentity('IF-MIB'))):

    if errorIndication:
        print(errorIndication)
        break
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

snmpwalk -v3 -lauthPriv -u usr-md5-none -A authkey1 -X privkey1 demo.snmplabs.com IF-MIB::

I am doing this for the according SNMP-v2 code and I get following difference in output:

sargon@....:~/workspace/private/pysnmp$ snmpwalk -v2c -c .... -m ALL .... IFMIB | wc -l
628

python3 test.py | wc
48083

For some reason that is more than data than expected, to be explicit that is the damn whole snmpwalk without reduction.

Permanently storing custom MIBs

I have been working with pySNMP for a little bit and was just successful in reaching an agent that runs a custom MIB. I have to work with several different systems that each run a custom MIB, and before I begin I want to confirm my thinking. It looks like if I load a MIB once, pySNMP stores it permanently. Is this correct?

For clarification, I originally had to perform a getCmd to get the name of an agent where my varBinds parameter was ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)).addAsn1MibSource(file_path)
Now, I only have to input ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) to achieve the same result.

If I am correct, how does pySNMP know the correct directory from which to read imported MIB? If not, how does pySNMP know how to access an agent?

cmdGen.getCmd with multiple oid returns failure for all oids even if only one fails

Using code similar to this example, when I passed in 4 oid's for my ink jet's color cartridges, I got "no such object currently exists at this oid" for each object. All error status were 0 so cmdGen.getCmd thought it returned successfully. Only one of the OID's was incorrect but all 4 returned the same message.

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    '1.3.6.1.2.1.1.1.0',
    '1.3.6.1.2.1.1.6.0'
)

# Check for errors and print out results
if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1] or '?'
            )
        )
    else:
        for name, val in varBinds:
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

Desired results would be to return the correct value for each oid and return the error message only on the one that actually failed.

Building pysnmp on Ubuntu ppc64le VM

Hi,

I am trying to port pysnmp package on Linux ppc64le Ubuntu VM.
But when I try to run the runtests.sh script, I get the following error

root@826f2f0aa536:/etingof/pysnmp# sh runtests.sh
Traceback (most recent call last):
  File "examples/hlapi/asyncore/sync/manager/cmdgen/coerce-set-value-to-mib-spec.py", line 17, in <module>
    from pysnmp.hlapi import *
ImportError: No module named pysnmp.hlapi

However the pysnmp package does have the pysnmp/hlapi

root@826f2f0aa536:/etingof/pysnmp# ls pysnmp/hlapi
__init__.py  asyncio  asyncore  auth.py  context.py  lcd.py  transport.py  twisted  varbinds.py

Tried to include the hlapi path in the environment variable PATH, but still didnt help.

Any pointer on how to resolve this would be helpful.

Thanks.

Regards,
Archa

TCP-over-IPv4

I am working on a company which uses pysnmp for a cloud printing solution - aiwip.com

We are finding that UCP is causing false negatives in our production codebase since we treat not being able to query the printer as an error.

I read here that TCP support is something of a future development http://pysnmp.sourceforge.net/development.html

What would be the steps needed for us to contribute this to the project to add support for TCP ?

Set Bulk Command

Hi, how to set value to multiple oid(more than 10000).
I need Set_Bulk_command.

When is use setCmd, i gave connection time out.

please help me!

ignoreNonIncreasingOid not working?

found this Link: http://pysnmp.sourceforge.net/faq/oids-not-increasing.html
tried to use cmdGen.ignoreNonIncreasingOid = True but the error remains: OIDs not increasing. With snmpwalk and -Cc its working like expected.

Sth i missed?


code:
from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()
cmdGen.ignoreNonIncreasingOid = True # doesnt matter if present or not!
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
cmdgen.CommunityData('public'),
cmdgen.UdpTransportTarget(("MyIP", MyPort)),
'1.3.6.1.2.1.17.7.1.2.2.1.2',
)

if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

[Question] Wrong usage? wrong document? or bug? About varBinds of bulkCmd in asynccore/asyncio

I'm not really sure if my usage is wrong/ the document is wrong/ or a bug.

The document said

varBinds (tuple): A sequence of sequences (e.g. 2-D array) of ObjectType class instances representing a table of MIB variables returned in SNMP response. Inner sequences represent table rows and ordered exactly the same as varBinds in request. Number of rows might be less or equal to maxRepetitions value in request.

http://pysnmp.sourceforge.net/docs/hlapi/asyncore/manager/cmdgen/bulkcmd.html#getbulk-command
http://pysnmp.sourceforge.net/docs/hlapi/asyncio/manager/cmdgen/bulkcmd.html#getbulk-command

So I thought the order of appearance of ObjectType in a returned varBinds is equal to the one in an argument.
Additionally I found a code to make lexicographicMode in sync-mode so I tried to make lexicographicMode=False like feature with asyncio like:

# varBinds := [ObjectType('mib-2.4.22.1.2'), ObjectType('mib-2.4.22.1.3')]
# result = Result(*await bulkCmd(..., *varBinds))
# ...
        for row in result.varBinds:
            print([x[0].prettyPrint() for x in row])
            for c, col in enumerate(row):
                if not objectIdentities[c].isPrefixOf(col[0]):
                    print('Escaped from the scope', col)

But actually the order of appearance of ObjectType in rows were different from my expectation

['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.3', 'SNMPv2-SMI::mib-2.4.22.1.3.27.10.10.0.3']
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.101', 'SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.102']
Escaped from the scope SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.102 = 0x784f43835a20
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.103', 'SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.106']
Escaped from the scope SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.106 = 0x6480994d9e54
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.107', 'SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.108']
Escaped from the scope SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.108 = 0x00220c23c840
...
Done asynccore
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.3', 'SNMPv2-SMI::mib-2.4.22.1.3.27.10.10.0.3']
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.101', 'SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.102']
Escaped from the scope SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.102 = 0x784f43835a20
['SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.103', 'SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.106']
Escaped from the scope SNMPv2-SMI::mib-2.4.22.1.2.27.10.10.0.106 = 0x6480994d9e54
...
Done asyncio

So I wonder if my usage is wrong or the document is wrong, or bug.

Thanks for reading 😄


The entire code I used is

from collections import namedtuple
from pysnmp.hlapi.varbinds import CommandGeneratorVarBinds

IP_NET_TO_MEDIA_PHYS_ADDRESS = '1.3.6.1.2.1.4.22.1.2'
IP_NET_TO_MEDIA_NET_ADDRESS = '1.3.6.1.2.1.4.22.1.3'

Result = namedtuple('Result', [
    'errorIndication',
    'errorStatus',
    'errorIndex',
    'varBinds',
])


def with_asynccore():
    from pysnmp.hlapi import asyncore as pysnmp

    snmpEngine = pysnmp.SnmpEngine()
    communityData = pysnmp.CommunityData('public')
    transportTarget = pysnmp.UdpTransportTarget(('10.10.0.1', 161))
    objectTypes = [
        pysnmp.ObjectType(pysnmp.ObjectIdentity(IP_NET_TO_MEDIA_PHYS_ADDRESS)),
        pysnmp.ObjectType(pysnmp.ObjectIdentity(IP_NET_TO_MEDIA_NET_ADDRESS)),
    ]
    vbproc = CommandGeneratorVarBinds()
    objectIdentities = [
        x[0] for x in vbproc.makeVarBinds(snmpEngine, objectTypes)
    ]

    def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
              errorIndex, varBinds, cbCtx):
        for row in varBinds:
            print([x[0].prettyPrint() for x in row])
            for c, col in enumerate(row):
                if not objectIdentities[c].isPrefixOf(col[0]):
                    print('Escaped from the scope', col)

    snmpEngine = pysnmp.SnmpEngine()
    pysnmp.bulkCmd(snmpEngine,
                   communityData,
                   transportTarget,
                   pysnmp.ContextData(),
                   0, 10,
                   *objectTypes,
                   cbFun=cbFun)
    snmpEngine.transportDispatcher.runDispatcher()
    print('Done asynccore')


def with_asyncio():
    import asyncio
    from pysnmp.hlapi import asyncio as pysnmp

    snmpEngine = pysnmp.SnmpEngine()
    communityData = pysnmp.CommunityData('public')
    transportTarget = pysnmp.UdpTransportTarget(('10.10.0.1', 161))
    objectTypes = [
        pysnmp.ObjectType(pysnmp.ObjectIdentity(IP_NET_TO_MEDIA_PHYS_ADDRESS)),
        pysnmp.ObjectType(pysnmp.ObjectIdentity(IP_NET_TO_MEDIA_NET_ADDRESS)),
    ]
    vbproc = CommandGeneratorVarBinds()
    objectIdentities = [
        x[0] for x in vbproc.makeVarBinds(snmpEngine, objectTypes)
    ]

    async def run(varBinds):
        result = Result(*await pysnmp.bulkCmd(snmpEngine,
                                              communityData,
                                              transportTarget,
                                              pysnmp.ContextData(),
                                              0, 10,
                                              *varBinds))
        for row in result.varBinds:
            print([x[0].prettyPrint() for x in row])
            for c, col in enumerate(row):
                if not objectIdentities[c].isPrefixOf(col[0]):
                    print('Escaped from the scope', col)

        snmpEngine.transportDispatcher.runDispatcher()

    asyncio.get_event_loop().run_until_complete(run(objectTypes))
    print('Done asyncio')

with_asynccore()

with_asyncio()

Missing top.html for building doc

Hi,

I could not make html doc, looks it's because of missing top.html, this issue happens in 4.3.1 and 4.3.2, also in current git repo:

Exception occurred:
  File "/usr/lib64/python2.7/site-packages/sphinx/jinja2glue.py", line 159, in get_source
    raise TemplateNotFound(template)
TemplateNotFound: top.html

Install pycrpytodome when installing for Windows

With the switch to pycryptodome (#19), pycyptodome provides binary wheel distributions for Windows.

It shouldn't be a problem to always install pycryptodome on Windows, though technically there are only wheels for 2.7, 3.3, 3.4, and 3.5. I suspect it's unlikely that someone on Windows is using a version of Python other than those.

https://github.com/etingof/pysnmp/blob/master/setup.py#L77-L88

        if sys.platform.lower()[:3] != 'win':
            params['requires'].append('pycryptodome')

if sys.platform.lower()[:3] == 'win':
    try:
        import Crypto
    except ImportError:
        sys.stderr.write("""WARNING! WARNING! WARNING!
PyCrypto binaries are required for SNMPv3 encryption to work.
You may wish to grab them from http://www.voidspace.org.uk/python/modules.shtml
and install into your system.
""")

Row consistency check failed for MibScalarInstance

This started showing up about a day ago and I'm not having much luck with finding a solution.

02:01:00,437: WARNING/PoolWorker-1] 2017-03-27 02:01:00,437 pysnmp: getValue: returning RowStatus('active') for (1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8, 115, 54, 57, 56, 55, 49, 50, 51, 53, 57, 56, 54, 49, 57, 49, 52, 52, 53, 57, 50)
[2017-03-27 02:01:00,437: DEBUG/PoolWorker-1] getValue: returning RowStatus('active') for (1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8, 115, 54, 57, 56, 55, 49, 50, 51, 53, 57, 56, 54, 49, 57, 49, 52, 52, 53, 57, 50)
[2017-03-27 02:01:00,437: WARNING/PoolWorker-1] 2017-03-27 02:01:00,437 pysnmp: flipFlopFsm: fun <bound method MibTree.readGet of MibTree((1,), None)> suceeded for (1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8, 115, 54, 57, 56, 55, 49, 50, 51, 53, 57, 56, 54, 49, 57, 49, 52, 52, 53, 57, 50)='createAndGo'
[2017-03-27 02:01:00,437: DEBUG/PoolWorker-1] flipFlopFsm: fun <bound method MibTree.readGet of MibTree((1,), None)> suceeded for (1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8, 115, 54, 57, 56, 55, 49, 50, 51, 53, 57, 56, 54, 49, 57, 49, 52, 52, 53, 57, 50)='createAndGo'
[2017-03-27 02:01:00,437: WARNING/PoolWorker-1] 2017-03-27 02:01:00,437 pysnmp: flipFlopFsm: state readGet status ok -> fsmState stop
[2017-03-27 02:01:00,437: DEBUG/PoolWorker-1] flipFlopFsm: state readGet status ok -> fsmState stop
[2017-03-27 02:01:00,439: WARNING/PoolWorker-1] === Traceback ===
[2017-03-27 02:01:00,440: WARNING/PoolWorker-1] Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 367, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 622, in __protected_call__
    return self.run(*args, **kwargs)
  File "/opt/code/lpiner/python/tasks.py", line 168, in clear_line
    SNMP.clear_line_v2(hostname, port, line_number, community)
  File "/opt/code/lpiner/python/modules/snmp.py", line 35, in clear_line_v2
    result = next(g)
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/hlapi/asyncore/sync/cmdgen.py", line 217, in setCmd
    lookupMib=options.get('lookupMib', True)))
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/hlapi/asyncore/cmdgen.py", line 235, in setCmd
    addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget)
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/hlapi/lcd.py", line 48, in configure
    authData.securityName
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/entity/config.py", line 88, in addV1System
    (snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo'))
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/smi/instrum.py", line 256, in writeVars
    return self.flipFlopFsm(self.fsmWriteVar, varBinds, acInfo)
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/smi/instrum.py", line 242, in flipFlopFsm
    raise origExc.with_traceback(origTraceback)
  File "/usr/local/lib/python3.5/dist-packages/pysnmp/smi/instrum.py", line 221, in flipFlopFsm
    rval = f(tuple(name), val, idx, acInfo)
  File "<string>", line 502, in writeCommit
  File "<string>", line 1174, in writeCommit
pysnmp.smi.error.InconsistentValueError: InconsistentValueError({'msg': 'Row consistency check failed for MibScalarInstance((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 2, 115, 54, 57, 56, 55, 49, 50, 51, 53, 57, 56, 54, 49, 57, 49, 52, 52, 53, 57, 50), OctetString())'})

Here is the calling code:

        g = setCmd(SnmpEngine(),
               CommunityData(community),
               UdpTransportTarget((hostname, 161)),
               ContextData(),
               ObjectType(ObjectIdentity('OLD-CISCO-TS-MIB', 'tsClrTtyLine', 0).addMibSource(Configuration().app_root + '/resources/MIBS'), int(line_number)))
        result = next(g)

And I won't post the compiled MIB unless needed but it here is the compilation info:

#
# PySNMP MIB module OLD-CISCO-TS-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/OLD-CISCO-TS-MIB
# Produced by pysmi-0.0.7 at Thu Mar  9 17:35:10 2017
# On host LPINER-M-V18L platform Darwin version 15.5.0 by user larkinpiner
# Using Python version 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
#

Error happened when dst IP is in the case: TTL expired

Software Version:
Python3.4/3.3
ply (3.10)
pyasn1 (0.2.3)
pycrypto (2.6.1)
pycryptodome (3.4.6)
pysmi (0.1.3)
pysnmp (4.3.8)
Windows2008R2

Error happened when TTL expired:
Pinging 192.168.245.2 with 32 bytes of data:
Reply from 192.168.252.3: TTL expired in transit.
Reply from 192.168.252.3: TTL expired in transit.
Reply from 192.168.252.3: TTL expired in transit.
Reply from 192.168.252.3: TTL expired in transit.

Ping statistics for 192.168.245.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)

Error:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 155, in handle_read
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 38, in __recvfrom
OSError: [WinError 10052] The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dispatch.py", line 46, in runDispatcher
File "C:\Python34\lib\asyncore.py", line 212, in loop
poll_fun(timeout, map)
File "C:\Python34\lib\asyncore.py", line 153, in poll
read(obj)
File "C:\Python34\lib\asyncore.py", line 87, in read
obj.handle_error()
File "C:\Python34\lib\asyncore.py", line 83, in read
obj.handle_read_event()
File "C:\Python34\lib\asyncore.py", line 442, in handle_read_event
self.handle_read()
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 171, in handle_read
pysnmp.carrier.error.CarrierError: recvfrom() failed: [WinError 10052] The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Administrator\Dropbox (NT)\multi-vendor support\Mimic Files\Scripts\SNMP.py", line 83, in
SNMP_set_hostname(dit[1], dit[0])
File "C:\Users\Administrator\Dropbox (NT)\multi-vendor support\Mimic Files\Scripts\SNMP.py", line 33, in SNMP_set_hostname
lookupValues=True
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\entity\rfc3413\oneliner\cmdgen.py", line 200, in setCmd
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\hlapi\asyncore\sync\cmdgen.py", line 219, in setCmd
File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dispatch.py", line 50, in runDispatcher
pysnmp.error.PySnmpError: poll error: Traceback (most recent call last):
; File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 155, in handle_read
incomingMessage, transportAddress = self._recvfrom(self.socket, 65535)
; File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 38, in __recvfrom
d, a = s.recvfrom(sz)
;OSError: [WinError 10052] The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress
;
During handling of the above exception, another exception occurred:

;Traceback (most recent call last):
; File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dispatch.py", line 46, in runDispatcher
use_poll=True, map=self.__sockMap, count=1)
; File "C:\Python34\lib\asyncore.py", line 212, in loop
poll_fun(timeout, map)
; File "C:\Python34\lib\asyncore.py", line 153, in poll
read(obj)
; File "C:\Python34\lib\asyncore.py", line 87, in read
obj.handle_error()
; File "C:\Python34\lib\asyncore.py", line 83, in read
obj.handle_read_event()
; File "C:\Python34\lib\asyncore.py", line 442, in handle_read_event
self.handle_read()
; File "C:\Python34\lib\site-packages\pysnmp-4.3.8-py3.4.egg\pysnmp\carrier\asyncore\dgram\base.py", line 171, in handle_read
raise error.CarrierError('recvfrom() failed: %s' % (sys.exc_info()[1],))
;pysnmp.carrier.error.CarrierError: recvfrom() failed: [WinError 10052] The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress

TypeError in pysnmp/proto/api/v1.py with pyasn1==0.2.3

$ cat reproduce.py
#!/usr/bin/env python

from pysnmp.hlapi import *

ip = '<REDACTED>'
community = '<REDACTED>'

errorIndication, errorStatus, errorIndex, varBinds = next(
    getCmd(SnmpEngine(),
           CommunityData(community, mpModel=0),
           UdpTransportTarget((ip, 161)),
           ContextData(),
           ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0).addAsn1MibSource('file:///usr/share/mibs/iana','file:///usr/share/mibs/ietf'))))
$ python reproduce.py
Traceback (most recent call last):
  File "reproduce.py", line 13, in <module>
    ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0).addAsn1MibSource('file:///usr/share/mibs/iana','file:///usr/share/mibs/ietf'))))
  File "/usr/local/lib/python3.6/site-packages/pysnmp/hlapi/asyncore/sync/cmdgen.py", line 111, in getCmd
    lookupMib=options.get('lookupMib', True)))
  File "/usr/local/lib/python3.6/site-packages/pysnmp/hlapi/asyncore/cmdgen.py", line 131, in getCmd
    options.get('cbFun'), options.get('cbCtx'))
  File "/usr/local/lib/python3.6/site-packages/pysnmp/entity/rfc3413/cmdgen.py", line 214, in sendVarBinds
    v2c.apiPDU.setVarBinds(reqPDU, varBinds)
  File "/usr/local/lib/python3.6/site-packages/pysnmp/proto/api/v1.py", line 136, in setVarBinds
    varBindList.getComponentByPosition(idx), varBind
  File "/usr/local/lib/python3.6/site-packages/pysnmp/proto/api/v1.py", line 43, in setOIDVal
    verifyConstraints=False)
TypeError: setComponentByType() got multiple values for argument 'verifyConstraints'

Python versions tested:

  • Python 3.6.0
  • Python 2.7.13

Python 3 modules

$ pip freeze
lxml==3.7.3
mock==2.0.0
ntlm-auth==1.0.2
ordereddict==1.1
pbr==1.10.0
pika==0.10.0
ply==3.10
pyasn1==0.2.3
pycryptodome==3.4.5
pysmi==0.0.7
pysnmp==4.3.3
python-logstash==0.4.6
requests==2.13.0
requests-ntlm==1.0.0
six==1.10.0
suds-jurko==0.6

Python 2 modules

(slightly different)

$ pip freeze
appdirs==1.4.0
ftntlib==0.3.3
funcsigs==1.0.2
ipaddress==1.0.18
lxml==3.7.3
mock==2.0.0
ntlm-auth==1.0.2
ordereddict==1.1
packaging==16.8
pbr==1.10.0
pika==0.10.0
ply==3.10
pyasn1==0.2.3
pyciapi==0.2
pycryptodome==3.4.5
pyparsing==2.1.10
pysmi==0.0.7
pysnmp==4.3.3
python-logstash==0.4.6
requests==2.13.0
requests-ntlm==1.0.0
six==1.10.0
suds-jurko==0.6
virtualenv==15.1.0

This can worked around by downgrading to pyasn1==0.2.2.

'instanceIndex=(0,)' caused exception SmiError as “ValueRangeConstraint(1, 2147483647) failed at: ”0“” at Integer32

I am new for python and SNMP (as well as pysnmp). After two weeks study, I wrote a piece of python code which try to send a trap message.
The NotificationType was created by code: (pysnmp 4.3.2)

   notification = NotificationType(ObjectIdentity('MY_MIB_FILE','myAlarmCleared'),
                                    instanceIndex=(0,),  
                                    objects={
                                        ('MY_MIB_FILE', 'myAlarmId'):
                                            Integer32(111),
                                        ('MY_MIB_FILE', 'mySystemDN'):
                                            self.DisplayString(''),  # currently a null string
                                        ('MY_MIB_FILE', 'myAlarmNotificationSource'):
                                            ObjectIdentifier(
                                                (1, 3, 6, 1, 4)), # some dummy value
                                        ('MY_MIB_FILE', 'myNotiSequenceNum'):
                                            Integer32(222),
                                        ('MY_MIB_FILE', 'myAlarmManagedObjectInstance'):
                                            self.DisplayString('SubNetwork=nw1,ManagedElement=my-1'),
                                        ('MY_MIB_FILE', 'myAlarmType'):
                                            self.AlarmType(3),
                                        ('MY_MIB_FILE', 'myAlarmProbableCause'):
                                            self.ProbableCause(307),
                                        ('MY_MIB_FILE', 'myAlarmSpecificProblem'):
                                            self.DisplayString('test alarm'),
                                        ('MY_MIB_FILE', 'myAlarmPerceivedSeverity'):
                                            self.AlarmSeverity(6),
                                        ('MY_MIB_FILE', 'myAlarmTime'):
                                            self.DateAndTime(OctetString(self.get_current_date_and_time())),
                                        ('MY_MIB_FILE', 'myAlarmAdditionalText'):
                                            self.DisplayString('alarm testing'),
                                        ('MY_MIB_FILE', 'myAlarmName'):
                                            self.DisplayString('system_testing_alarm'),
                                        ('MY_MIB_FILE', 'myAlarmServiceUser'):
                                            self.DisplayString('Dapeng Jiao'),
                                        ('MY_MIB_FILE', 'myAlarmServiceProvider'):
                                            self.DisplayString('Unknown Service Provider'),
                                        ('MY_MIB_FILE', 'myAlarmSecurityAlarmDetector'):
                                            self.DisplayString('Unknown Alarm Detector'),
                                        ('MY_MIB_FILE', 'myAlarmADMC'):
                                            Integer(1)
                                    }
                                    )

when I execute this code, I got following SmiError:

  File "/vagrant_data/snmpAgent/SOURCES/snmp_notifier_v3.py", line 142, in notifier_start
    cbFun=cbfun
  File "/usr/lib/python2.7/site-packages/pysnmp/hlapi/asyncore/ntforg.py", line 145, in sendNotification
    vbProcessor.makeVarBinds(snmpEngine, varBinds),
  File "/usr/lib/python2.7/site-packages/pysnmp/hlapi/varbinds.py", line 51, in makeVarBinds
    varBinds.resolveWithMib(mibViewController)
  File "/usr/lib/python2.7/site-packages/pysnmp/smi/rfc1902.py", line 1143, in resolveWithMib
    objectIdentity = ObjectIdentity(*notificationObject+self.__instanceIndex).resolveWithMib(mibViewController)
  File "/usr/lib/python2.7/site-packages/pysnmp/smi/rfc1902.py", line 504, in resolveWithMib
    raise SmiError('Instance index %r to OID convertion failure at object %r: %s' % (self.__args[2:], mibNode.getLabel(), sys.exc_info()[1]))
pysnmp.smi.error.SmiError: Instance index (0,) to OID convertion failure at object 'myAlarmTime': ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(-2147483648, 2147483647)), ValueRangeConstraint(1, 2147483647)) failed at: "ValueRangeConstraint(1, 2147483647) failed at: "0"" at Integer32

It seems pysnmp doesn't like to add suffix .0 for the variable whose syntax is defined as:

Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite")

Does it a bug for pysnmp?
Or I should not add that .0 suffix?(at least after remove that '0,' from instanceIndex the code can be executed and trap message sent successfully.
But I was told that

A scalar variable has single instance and is identified by suffix .0 .
The object identifier (OID) with .0 suffix indicates a scalar variable (i.e., single instance) (eg, analogous/category of a “table” with only one column)
Each of the varbinds in the notification is scalar for this alarm notification.

Also there is a explanation about Scalar and Tabular Objects: https://www.webnms.com/cagent/help/technology_used/c_snmp_overview.html#scalar&tabular
Scalar and Tabular Objects

A managed object has both a type (defined in ASN.1) and a value. For example, the SNMP system group variable sysLocation ( this variable is defined in RFC1213-MIB ) has the type, DisplayString and may have the value, "WebNMS Velachery". So in our case, we can define noOfPapers or inkLevel of the printer as a scalar object in the MIB.

Managed objects, in SNMP, are of two types : scalar objects and tabular objects.

A managed object that always has a single instance is called a scalar object. Tabular objects, on the other hand, have multiple instances, such as the rows of a table. For example, the MIB II system group has seven "leaf" variables under it, as illustrated in Figure below. Each of these objects is a scalar object. For example, the value of sysUpTime is the duration of time since re-initialization of a system's network management software (SNMP agent), measured in hundredths of a second.

Tables in SNMP are two-dimensional objects defined as an ASN.1 type called SEQUENCE OF, which allows 0 or more members. Each element of the sequence is an entry (row) in the table, which itself is a sequence of scalar-valued objects. SNMP does not allow tables to be nested within tables.

For example, the MIB II at group contains simply one tabular object, the atTable, which contains one row for each of a system's physical interfaces. Each row in the table is an instance of the object atEntry. Each row contains instances of the scalar-valued leaf objects atIfIndex, atPhysAddress, and atNetAddress. The leaf objects are called columnar objects since the instances of each such object constitute one column in the table. Although these objects have scalar-valued instances, they are not scalar objects because they can have multiple instances.

So seems the .0 is anyway needed, right? (Since it should be a object has a single instance.)
Or there are some misunderstanding from us?

Thanks in advance.

Br,
-Dapeng Jiao

The original MIB defination for that variable is:

myAlarmCleared NOTIFICATION-TYPE
    OBJECTS {
        myAlarmId,
        cesSystemDN,
        myAlarmNotificationSource,
        cesNotiSequenceNum,
        myAlarmManagedObjectInstance,
        myAlarmType,
        myAlarmProbableCause,
        myAlarmSpecificProblem,
        myAlarmPerceivedSeverity,
        myAlarmTime,
        myAlarmAdditionalText,
        myAlarmName,
        myAlarmServiceUser,
        myAlarmServiceProvider,
        myAlarmSecurityAlarmDetector,
        myAlarmADMC
    }
    STATUS  current
    DESCRIPTION
        "This notification is generated when an alarm is cleared."
    ::=  {  myAlarmNotifications  3  }

myAlarmTime OBJECT-TYPE
    SYNTAX  DateAndTime
    MAX-ACCESS  read-only
    STATUS  current
    DESCRIPTION
        "This variable is the time of this Alarm object."
    ::=  {  myAlarmEntry  9  }

myAlarmEntry OBJECT-TYPE
    SYNTAX  myAlarmEntry
    MAX-ACCESS  not-accessible
    STATUS  current
    DESCRIPTION
        "A row containing one alarm."
    INDEX   { myAlarmId }
    ::= { myAlarmTable 1 }

and converted python format is:

myAlarmCleared = NotificationType((1, 3, 6, 1, 4, 1, xxxx, x, xx, x, xxx, x, 6, 3)).setObjects(*(
("MY-MIB-FILE", "myAlarmTime"), ("MY-MIB-FILE", "myAlarmName"),
("MY-MIB-FILE", "myAlarmServiceUser"), ("MY-MIB-FILE", "myAlarmSpecificProblem"),
("MY-MIB-FILE", "cesSystemDN"), ("MY-MIB-FILE", "myAlarmProbableCause"),
("MY-MIB-FILE", "myAlarmType"), ("MY-MIB-FILE", "myAlarmAdditionalText"),
("MY-MIB-FILE", "myAlarmNotificationSource"), ("MY-MIB-FILE", "myAlarmId"),
("MY-MIB-FILE", "myAlarmManagedObjectInstance"), ("MY-MIB-FILE", "myAlarmADMC"),
("MY-MIB-FILE", "myAlarmSecurityAlarmDetector"),
("MY-MIB-FILE", "myAlarmPerceivedSeverity"), ("MY-MIB-FILE", "cesNotiSequenceNum"),
("MY-MIB-FILE", "myAlarmServiceProvider"),))

myAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, xxxx, x, xx, x, xxx, x, x, x, 1)).setIndexNames((0, "MY-MIB-FILE", "myAlarmId"))
if mibBuilder.loadTexts: myAlarmEntry.setDescription("A row containing one alarm.")

myAlarmTime = MibTableColumn((1, 3, 6, 1, 4, 1, xxxx, x, xx, x, xxx, x, x, 1, 1, 9), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myAlarmTime.setDescription("This variable is the time of this Alarm object.")

DateAndTime was imported from SNMPv2-TC.

One update for this:
Even the exception shows the problem is caused by 'myAlarmTime'

pysnmp.smi.error.SmiError: Instance index (0,) to OID convertion failure at object 'myAlarmTime': ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(-2147483648, 2147483647)), ValueRangeConstraint(1, 2147483647)) failed at: "ValueRangeConstraint(1, 2147483647) failed at: "0"" at Integer32

But after debug, it seems the real issue is 'myAlarmId' syntax definition. As that variable is the only one defined with Integer32 with range (1, 2147483647)

myAlarmId = MibTableColumn((1, 3, 6, 1, 4, 1, xxxx, x, xx, x, xxx, x, 4, 1, 1, 1),
                            Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")

And after I change its value range to (0, 2147483647), the
instanceIndex = (0,)
start to works.

But I should NOT change that right?
Then what should be the root cause for this issue?
Pysnmp bug?
or our misunderstanding for SNMP and MIB file?

BTW: the suffix .0 was working fine with a Java based SNMP cilent. But due to company's order and license issue, we need to re-implement it and we though python should be a good enough to do this.

Attach more MIB definition relate to this alarm event

myAlarmTable OBJECT-TYPE
    SYNTAX  SEQUENCE OF myAlarmEntry
    MAX-ACCESS  not-accessible
    STATUS  current
    DESCRIPTION
        "A table of all the active alarms on the system."
    ::= { myAlarmObjects 1 }

myAlarmEntry OBJECT-TYPE
    SYNTAX  myAlarmEntry
    MAX-ACCESS  not-accessible
    STATUS  current
    DESCRIPTION
        "A row containing one alarm."
    INDEX   { myAlarmId }
    ::= { myAlarmTable 1 }

myAlarmEntry ::=
    SEQUENCE {
        myAlarmId                   Integer32,
        mySystemDN                  DisplayString,
        myAlarmNotificationSource           OBJECT IDENTIFIER,
        myAlarmManagedObjectInstance        DisplayString,
        myAlarmType                 AlarmType,
        myAlarmProbableCause            ProbableCause,
        myAlarmSpecificProblem          DisplayString,
        myAlarmPerceivedSeverity            AlarmSeverity,
        myAlarmTime                 DateAndTime,
        myAlarmAdditionalText           DisplayString,
        myAlarmName                 DisplayString,
        myAlarmServiceUser              DisplayString,
        myAlarmServiceProvider          DisplayString,
        myAlarmSecurityAlarmDetector        DisplayString,
        myAlarmADMC         INTEGER
    }


myAlarmId OBJECT-TYPE
    SYNTAX  Integer32 (1..2147483647)
    MAX-ACCESS  read-only
    STATUS  current
    DESCRIPTION
        "This object uniquely identifies an entry in the
        Alarm Table. It increases every time a new alarm
        occurs. Due to cleared alarms the index will not be
        contiguous. When the maximum is reached of
        Integer32, the value of this object rolls over to 1."
    ::=  {  myAlarmEntry  1  }

Br,
-Dapeng Jiao

Exception raised when resolveWithMib() is invoked on a NotificationType containing objects imported from another MIB

Given the MIBs below, the following code raises an exception:

from pysnmp.smi import builder, view, compiler, rfc1902

mibBuilder = builder.MibBuilder()
mibViewController = view.MibViewController(mibBuilder)
compiler.addMibCompiler(mibBuilder, sources=['file:///tmp/mibs'])

mibBuilder.loadModules('SNMPv2-MIB', 'MY-MIB')

oid = rfc1902.ObjectIdentity('1.3.6.1.4.1.99999.2.1')
notificationType = rfc1902.NotificationType(oid).resolveWithMib(mibViewController)

Exception

Traceback (most recent call last):
  File ".../notification_test.py", line 10, in <module>
    notificationType = rfc1902.NotificationType(oid).resolveWithMib(mibViewController)
  File ".../python2.7/site-packages/pysnmp/smi/rfc1902.py", line 1158, in resolveWithMib
    mibViewController)
  File ".../python2.7/site-packages/pysnmp/smi/rfc1902.py", line 481, in resolveWithMib
    self.__modName, self.__symName
  File ".../python2.7/site-packages/pysnmp/smi/builder.py", line 407, in importSymbols
    'No symbol %s::%s at %s' % (modName, symName, self)
pysnmp.smi.error.SmiError: No symbol MY-MIB::otherMibObj at <pysnmp.smi.builder.MibBuilder object at 0x7eff222f3f50>

The root cause seems to be the following line of generated code in MY-MIB.py:

myMibNotification = NotificationType((1, 3, 6, 1, 4, 1, 99999, 2, 1)).setObjects(("MY-MIB", "otherMibObj"), ("MY-MIB", "myMibObj"))

When manually changed to the following, the exception no longer occurs:

myMibNotification = NotificationType((1, 3, 6, 1, 4, 1, 99999, 2, 1)).setObjects(("OTHER-MIB", "otherMibObj"), ("MY-MIB", "myMibObj"))

MY-MIB

MY-MIB DEFINITIONS ::= BEGIN

IMPORTS
    MODULE-IDENTITY, OBJECT-TYPE, TimeTicks, NOTIFICATION-TYPE, Integer32, enterprises
        FROM SNMPv2-SMI
    otherMibObj
        FROM OTHER-MIB;

myMib MODULE-IDENTITY
    LAST-UPDATED "201705181000Z" -- Thu May 18 10:00:00 PST 2017
    ORGANIZATION "My org"
    CONTACT-INFO "Me"
    DESCRIPTION "Example MIB"
    ::= { enterprises 99999 }

    myMibObj OBJECT-TYPE
        SYNTAX          Integer32 (1..1024)
        MAX-ACCESS      not-accessible
        STATUS          current
        DESCRIPTION "Example object"
        ::= { myMib 1 }

    myMibTraps OBJECT-IDENTITY
        STATUS  current
        DESCRIPTION "The root of all trap OIDs."
        ::= { myMib 2 }


    myMibNotification NOTIFICATION-TYPE
        OBJECTS {
                  otherMibObj,
                  myMibObj
                }
        STATUS  current
        DESCRIPTION
                "Example notification"
        ::= { myMibTraps 1 }

END

OTHER-MIB

OTHER-MIB DEFINITIONS ::= BEGIN

IMPORTS
    MODULE-IDENTITY, OBJECT-TYPE, Integer32, enterprises
        FROM SNMPv2-SMI;

otherMib MODULE-IDENTITY
    LAST-UPDATED "201705181000Z" -- Thu May 18 10:00:00 PST 2017
    ORGANIZATION "Other org"
    CONTACT-INFO "Other"
    DESCRIPTION "Example MIB"
    ::= { enterprises 99998 }

    otherMibObj OBJECT-TYPE
        SYNTAX          Integer32 (1..1024)
        MAX-ACCESS      not-accessible
        STATUS          current
        DESCRIPTION "Example object"
        ::= { otherMib 1 }


END

build-pysnmp-mib

What happened to that script and where can I find it? I use it to import mib files into pysnmp

PysnmpError with dispatch.py(49)

1.) When just calling something like 'sysDescr' in the SNMPv2-MIB I get results.

#!/usr/bin/env python

from pysnmp.hlapi import *
from pprint import pprint

community = 'communitypassword'
lb = 'f5ltm-host'

g = nextCmd(SnmpEngine(),
            CommunityData(community),
            UdpTransportTarget((lb, 161)),
            ContextData(),
            ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))

print next(g)

Produces:

(None, Integer('noError', NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5), ('noAccess', 6), ('wrongType', 7), ('wrongLength', 8), ('wrongEncoding', 9), ('wrongValue', 10), ('noCreation', 11), ('inconsistentValue', 12), ('resourceUnavailable', 13), ('commitFailed', 14), ('undoFailed', 15), ('authorizationError', 16), ('notWritable', 17), ('inconsistentName', 18))), Integer(0, subtypeSpec=ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(0, Integer(2147483647)))), [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('BIG-IP 1600 : Linux 2.6.32-431.56.1.el6.f5.x86_64 : BIG-IP software release 12.1.0, build 1.0.1447', subtypeSpec=ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueSizeConstraint(0, 65535)), ValueSizeConstraint(0, 255)), ValueSizeConstraint(0, 255))))])

2.) But when I call another object 'ltmPoolMemberMonitorStatus' from a MIB that is asn1 converted MIB 'F5-BIGIP-LOCAL-MIB' it produces an error:

The only line that changes was the ObjectType line:
Note: All required mibs seem to be 'loaded' after 'evaluation'

From:
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
To:
ObjectType(ObjectIdentity('F5-BIGIP-LOCAL-MIB', 'ltmPoolMemberMonitorStatus')))

#!/usr/bin/env python

from pysnmp.hlapi import *
from pprint import pprint

community = 'communitypassword'
lb = 'f5ltm-host'

g = nextCmd(SnmpEngine(),
            CommunityData(community),
            UdpTransportTarget((lb, 161)),
            ContextData(),
            ObjectType(ObjectIdentity('F5-BIGIP-LOCAL-MIB', 'ltmPoolMemberMonitorStatus')))

print next(g)

Produces:

Traceback (most recent call last):
File "/home/lhoffman/bbcom/python/f5zabbix/f5walk.py", line 19, in
print next(g)
File "/usr/local/lib/python2.7/dist-packages/pysnmp/hlapi/asyncore/sync/cmdgen.py", line 347, in nextCmd
snmpEngine.transportDispatcher.runDispatcher()
File "/usr/local/lib/python2.7/dist-packages/pysnmp/carrier/asyncore/dispatch.py", line 49, in runDispatcher
raise PySnmpError('poll error: %s' % ';'.join(format_exception(*exc_info())))
pysnmp.error.PySnmpError: poll error: Traceback (most recent call last):
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/carrier/asyncore/dispatch.py", line 45, in runDispatcher
use_poll=True, map=self.sockMap, count=1)
; File "/usr/lib/python2.7/asyncore.py", line 220, in loop
poll_fun(timeout, map)
; File "/usr/lib/python2.7/asyncore.py", line 201, in poll2
readwrite(obj, flags)
; File "/usr/lib/python2.7/asyncore.py", line 123, in readwrite
obj.handle_error()
; File "/usr/lib/python2.7/asyncore.py", line 108, in readwrite
obj.handle_read_event()
; File "/usr/lib/python2.7/asyncore.py", line 449, in handle_read_event
self.handle_read()
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/carrier/asyncore/dgram/base.py", line 157, in handle_read
self._cbFun(self, transportAddress, incomingMessage)
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/carrier/base.py", line 68, in _cbFun
self, transportDomain, transportAddress, incomingMessage
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/entity/engine.py", line 145, in __receiveMessageCbFun
self, transportDomain, transportAddress, wholeMsg
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/proto/rfc3412.py", line 458, in receiveMessage
cachedParams['cbCtx'])
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/entity/rfc3413/cmdgen.py", line 131, in processResponsePdu
cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/entity/rfc3413/cmdgen.py", line 274, in processResponseVarBinds
varBindTable, cbCtx):
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/hlapi/asyncore/cmdgen.py", line 336, in __cbFun
[vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable],
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/hlapi/varbinds.py", line 43, in unmakeVarBinds
varBinds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/smi/rfc1902.py", line 838, in resolveWithMib
self.__args[0].resolveWithMib(mibViewController)
; File "/usr/local/lib/python2.7/dist-packages/pysnmp/smi/rfc1902.py", line 446, in resolveWithMib
self.__indices = rowNode.getIndicesFromInstId(suffix)
; File "/tmp/pip-build-dm8da3/pysnmp/pysnmp/smi/mibs/SNMPv2-SMI.py", line 1150, in getIndicesFromInstId
; File "/tmp/pip-build-dm8da3/pysnmp/pysnmp/smi/mibs/SNMPv2-SMI.py", line 955, in setFromName
; File "/usr/local/lib/python2.7/dist-packages/pyasn1/type/univ.py", line 126, in clone
return self.__class
(value, tagSet, subtypeSpec, namedValues)
; File "/usr/local/lib/python2.7/dist-packages/pyasn1/type/univ.py", line 22, in init
self, value, tagSet, subtypeSpec
; File "/usr/local/lib/python2.7/dist-packages/pyasn1/type/base.py", line 75, in init
self._verifySubtypeSpec(value)
; File "/usr/local/lib/python2.7/dist-packages/pyasn1/type/base.py", line 33, in _verifySubtypeSpec
raise c('%s at %s' % (i, self.class.name))
;ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(-2147483648, 2147483647)), ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 16))) failed at: "ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 16)) failed at: "all of (SingleValueConstraint(0, 1, 2, 3, 4, 16),) failed for "13""" at InetAddressType

Can you tell me where to find out where the 'failed for "13" is coming form?
When I run this script as 'cont' inside the python debugger (pdb -m ./f5walk.py) I see this message in the "post mortem debugging'

/usr/local/lib/python2.7/dist-packages/pysnmp/carrier/asyncore/dispatch.py(49)runDispatcher()
-> raise PySnmpError('poll error: %s' % ';'.join(format_exception(*exc_info())))

Pyinstaller .exe errors when sending trap

I'm getting error "TypeError: getsockaddrarg() takes exactly 2 arguments (6 given)" when sending a trap after compiling into a windows .exe with Pyinstaller and the --onefile option. This is with the example code at http://pysnmp.sourceforge.net/examples/v3arch/asyncore/agent/ntforg/snmp-versions.html#snmpv1-trap . It works fine as a plain .py script.

if I add debugging to pysnmp/carrier/asyncore/dgram/base.py line 142

try:
            print("transportAddress: " + str(transportAddress))
            self._sendto(
                self.socket, outgoingMessage, transportAddress
            )

I see the following when it works as a .py script:
transportAddress: ('10.6.105.121', 162)

And the following when it fails as a Windows .exe

transportAddress: (10, 6, 105, 121, 0, 162)
Traceback (most recent call last):
  File "site-packages\pysnmp\carrier\asyncore\dispatch.py", line 46, in runDispatcher
  File "asyncore.py", line 212, in loop
  File "asyncore.py", line 159, in poll
  File "asyncore.py", line 95, in write
  File "asyncore.py", line 91, in write
  File "asyncore.py", line 461, in handle_write_event
  File "site-packages\pysnmp\carrier\asyncore\dgram\base.py", line 144, in handle_write
  File "site-packages\pysnmp\carrier\asyncore\dgram\base.py", line 35, in <lambda>
TypeError: getsockaddrarg() takes exactly 2 arguments (6 given)

If I modify base.py to fix transportAddress it starts working as a windows .exe

            print("transportAddress: " + str(transportAddress))
            if len(transportAddress) == 6:
              transportAddress = ( '.'.join(map(str,transportAddress[0:4])), transportAddress[5])
              print("NEW transportAddress: " + str(transportAddress))
            self._sendto(
                self.socket, outgoingMessage, transportAddress
            )
transportAddress: (10, 6, 105, 121, 0, 162)
NEW transportAddress: ('10.6.105.121', 162)

I'm not sure if this is necessarly an issue with pysnmp, pyinstaller, python on Windows, or if I should be adding additional code if I plan to compile to .exe

SNMP OID sysUpTime is missing one digit?

Hey, I encountered a problem parsing the return value of the sysUpTime request via SNMPv2 on out Fortinet and HP Equipment.

There is simply a digit missing when it comes to this request.
It returns 227821100 which is around 2.6 days!
When I multiple the number *10 and run it though my time-parser, it gives me the correct ~26 days.

It might be my code, but I didn't find the issue there, so I thought I'll open an issue.


def getSNMP(community, host, OID):
    iterator = getCmd(SnmpEngine(),
                      CommunityData(community),
                      UdpTransportTarget((host, 161)),
                      ContextData(),
                      ObjectType(ObjectIdentity('SNMPv2-MIB', OID, 0)))

    errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

    if errorIndication:  # SNMP engine errors
        print(errorIndication)
    else:
        if errorStatus:  # SNMP agent errors
            print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
        else:
            for varBind in varBinds:  # SNMP response contents
                #print(' = '.join([x.prettyPrint() for x in varBind]))
                return str(varBind).split("=",1)[-1].strip()

This is mostly the code you posted here on github, with a return instead of a print.

Here is my testing code:

    if (attribute == "uptime"):
        oid = 'sysUpTime'
        ms = int(getSNMP('public', host, oid))*10
        print(msToReadable(ms))

This already gived me the time with a missing digit, unless I add *10 at the end.

And here I'e got the conversion code.

def msToReadable(ms):
    x = ms / 1000
    seconds = x % 60
    x /= 60
    minutes = x % 60
    x /= 60
    hours = x % 24
    x /= 24
    days = x

    return str(days).split(".")[0] +  " days, " + str(hours).split(".")[0] + " hours, " + str(minutes).split(".")[0] + " minutes, " + str(seconds).split(".")[0] +" seconds" + ", or " + str(ms) + " ms"


It's not really clean, since I just wanted to test a few things, but I hope you can read through it without any problems!

Pysnmp Import error with PYSNMP 4.3.6

Hi,
With PYSNMP 4.3.6-- I am observing a new issue:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Python 2.7.8 (default, Dec 4 2014, 15:24:39)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import pysnmp
from pysnmp.entity.rfc3413.oneliner import ntforg
Traceback (most recent call last):
File "", line 1, in
File "/home/user/VIRT/lib/python2.7/site-packages/pysnmp/entity/rfc3413/oneliner/ntforg.py", line 1, in
pysnmp/carrier/asyncore/dgram/base.py#
NameError: name 'pysnmp' is not defined
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Reason is in ntforg.py the 1st line creating this problem.

$ cat ntforg.py|head
pysnmp/carrier/asyncore/dgram/base.py#


The issue was not observed in 4.3.5.

Importing custom mibs

I'm trying to import some custom MIB files and I'm not getting the output I'd expect. A large amount of the modules aren't being shown. I'm using your SNMP MIB browser template. I found a stacked overflow article on how the MIB files need to be formatted to pysnmp format first. According to the docs this appears to be automated now so that might not be the issue. I'm just trying to get a browser / parser for the Oids and their names.

SmiError: Excessive instance identifier sub-OIDs left at MibTableRow

Hi,

I'm trying to extract some values from a Ruckus ZoneDirector (https://raw.githubusercontent.com/librenms/librenms/master/mibs/RUCKUS-ZD-WLAN-MIB), specifically ruckusZDWLANAPStatus field.

ruckusZDWLANAPStatus field is from table ruckusZDWLANAPTable (.1.3.6.1.4.1.25053.1.2.2.1.1.2.1)

Output from snmpwalk is:

SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.83.176 = Hex-STRING: 2C C5 D3 33 53 B0
SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.87.0 = Hex-STRING: 2C C5 D3 33 57 00
SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.90.144 = Hex-STRING: 2C C5 D3 33 5A 90
SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.90.192 = Hex-STRING: 2C C5 D3 33 5A C0
SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.104.112 = Hex-STRING: 2C C5 D3 33 68 70
SNMPv2-SMI::enterprises.25053.1.2.2.1.1.2.1.1.1.6.44.197.211.51.104.144 = Hex-STRING: 2C C5 D3 33 68 90

I wonder if pysnmp handles these kinds of sequence where index is not a simple number.

Pysnmp 4.3.2.

jfr

Setting Source IP from Highlevel API

Hi,
I am facing the problem to set the source IP of our snmp requests and didn't find a way to do it via the highlevel API. Is this intended or is there an undocumented way to do it or did I missed it in the docs? I'm using the asyncio highlevel API.

Thanks for any help!

AttributeError: 'module' object has no attribute 'noValue'

I'm getting this error with both 4.3.5 and 4.3.8. Python version is 2.7.13

Below is a stack trace from a simple app that I wrote which uses pysnmp to read SNMP data (Sorry for the layout -- I tried to insert them as code but that doesn't seem to work):

Traceback (most recent call last): File "/usr/lib64/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib64/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/app/empf/lib/python/monitor-0.1.0-py2.7.egg/monitor/__main__.py", line 22, in <module> app() File "/app/lib/python/monitor-0.1.0-py2.7.egg/monitor/matrix.py", line 115, in __call__ result = self.run(job) File "/app/lib/python/monitor-0.1.0-py2.7.egg/monitor/matrix.py", line 48, in run mod = __import__('monitor.'+job.type, fromlist=[job.type], level=1) File "/app/lib/python/monitor-0.1.0-py2.7.egg/monitor/AsyncSNMPv1.py", line 16, in <module> from pysnmp.entity.rfc3413.oneliner import cmdgen File "/app/lib/python/gevent-1.2.1-py2.7-linux-x86_64.egg/gevent/builtins.py", line 93, in __import__ result = _import(*args, **kwargs) File "/usr/lib/python2.7/site-packages/pysnmp/entity/rfc3413/oneliner/cmdgen.py", line 10, in <module> from pysnmp.hlapi.asyncore import * File "/app/lib/python/gevent-1.2.1-py2.7-linux-x86_64.egg/gevent/builtins.py", line 93, in __import__ result = _import(*args, **kwargs) File "/usr/lib/python2.7/site-packages/pysnmp/hlapi/__init__.py", line 7, in <module> from pysnmp.proto.rfc1902 import * File "/app/lib/python/gevent-1.2.1-py2.7-linux-x86_64.egg/gevent/builtins.py", line 93, in __import__ result = _import(*args, **kwargs) File "/usr/lib/python2.7/site-packages/pysnmp/proto/rfc1902.py", line 563, in <module> class Bits(OctetString): File "/usr/lib/python2.7/site-packages/pysnmp/proto/rfc1902.py", line 614, in Bits def __init__(self, value=univ.noValue, tagSet=None, subtypeSpec=None, AttributeError: 'module' object has no attribute 'noValue'

SNMPv1 get results ignored/dropped?

Here is an test example (snmpget from Net-SNMP vs pysnmp 4.2.5-1 on Ubuntu 16.04.1):

$ snmpget -d -c public -v 1 10.23.65.65 .1.3.6.1.4.1.29660.2.3.2.0

Sending 47 bytes to UDP: [10.23.65.65]:161->[0.0.0.0]:0
0000: 30 2D 02 01 00 04 06 70 75 62 6C 69 63 A0 20 02 0-.....public. .
0016: 04 18 F3 6C 4B 02 01 00 02 01 00 30 12 30 10 06 ...lK......0.0..
0032: 0C 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00 .+............

Received 49 byte packet from UDP: [10.23.65.65]:161->[0.0.0.0]:36079
0000: 30 2F 02 01 00 04 06 70 75 62 6C 69 63 A2 22 02 0/.....public.".
0016: 04 18 F3 6C 4B 02 01 00 02 01 00 30 14 30 12 06 ...lK......0.0..
0032: 0C 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 .+.............
0048: 35 5

iso.3.6.1.4.1.29660.2.3.2.0 = INTEGER: 565

$ pysnmpget -d -c public -v 1 10.23.65.65 1.3.6.1.4.1.29660.2.3.2.0
DBG: [10:42:39.482]: running pysnmp version 4.2.5
DBG: [10:42:39.482]: debug category 'io' enabled
DBG: [10:42:39.496]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:39.496]: handle_write: transportAddress ('0.0.0.0', 0) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:39.510]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
DBG: [10:42:40.514]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:40.515]: handle_write: transportAddress ('0.0.0.0', 42116) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:40.527]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
DBG: [10:42:41.532]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:41.532]: handle_write: transportAddress ('0.0.0.0', 42116) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:41.543]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
DBG: [10:42:42.547]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:42.548]: handle_write: transportAddress ('0.0.0.0', 42116) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:42.560]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
DBG: [10:42:43.563]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:43.564]: handle_write: transportAddress ('0.0.0.0', 42116) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:43.577]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
DBG: [10:42:44.580]: sendMessage: outgoingMessage queued (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:44.580]: handle_write: transportAddress ('0.0.0.0', 42116) -> ('10.23.65.65', 161) outgoingMessage (46 octets)
00000: 30 2C 02 01 00 04 06 70 75 62 6C 69 63 A0 1F 02
00016: 03 17 11 34 02 01 00 02 01 00 30 12 30 10 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 05 00
DBG: [10:42:44.594]: handle_read: transportAddress ('10.23.65.65', 161) -> ('0.0.0.0', 42116) incomingMessage (48 octets)
00000: 30 2E 02 01 00 04 06 70 75 62 6C 69 63 A2 21 02
00016: 03 17 11 34 02 01 00 02 01 00 30 14 30 12 06 0C
00032: 2B 06 01 04 01 81 E7 5C 02 03 02 00 02 02 02 35
No SNMP response received before timeout

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.