Giter Club home page Giter Club logo

python-snmp's Introduction

Installation

This library is available in PyPi under the name snmp. Installation is as simple as

pip install snmp

Documentation

Documentation for this library, including a simple tutorial and a library reference, is available in ReadTheDocs.

python-snmp's People

Contributors

charlestolley avatar

Stargazers

A'rpi avatar Denis Bondar avatar  avatar Uffe Jakobsen avatar Martin Beckert avatar Dhruvin Shah avatar Ricardo Gutierrez avatar TBS Support avatar Krisque avatar  avatar  avatar  avatar José Eduardo Brandão avatar

Watchers

Lex Li avatar James Cloos avatar Chaaly avatar  avatar

python-snmp's Issues

SNMPv1 when the endOfMib is reached, an ErrorResponse is thrown

If the response error-status field is not 0, an ErrorResponse exception is thrown, to which pdu.errorStatus and pdu.errorIndex are passed. But it is impossible to get these two important values from the exception instance.

The need for these values can be caused, for example, by the fact that in SNMPv1, when reaching the end of the tree, the agent passes error-status=2 (endOfMib).

If execute getNext in the loop, at some point you may get an ErrorResponse exception and there is no way to know the value of the error-status field.

Maybe this problem can be solved differently by throwing some EndOfMib exception at manager (v1), because the described problem is typical for SNMPv1.

SNMPv2c - TypeError: can't concat str to bytes

Hi!

I'm trying to use snmp 0.5.0 inside a docker container with Ubuntu and Python 3.11.3 installed.
When I try to execute the following code from the documentation:

from snmp import Engine, SNMPv2c

with Engine(SNMPv2c, defaultCommunity="public") as engine:
    localhost = engine.Manager("127.0.0.1")
    response = localhost.get("1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.6.0")
    print(response)

I receive the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 5
      3 with Engine(SNMPv2c, defaultCommunity="public") as engine:
      4     localhost = engine.Manager("127.0.0.1")
----> 5     response = localhost.get("1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.6.0")
      6     print(response)

File /opt/conda/lib/python3.11/site-packages/snmp/manager/v2c.py:164, in SNMPv2cManager.get(self, *oids, **kwargs)
    162 def get(self, *oids, **kwargs):
    163     pdu = GetRequestPDU(*oids)
--> 164     return self.sendRequest(pdu, **kwargs)

File /opt/conda/lib/python3.11/site-packages/snmp/manager/v2c.py:155, in SNMPv2cManager.sendRequest(self, pdu, community, wait, **kwargs)
    153 with self.lock:
    154     heapq.heappush(self.requests, reference)
--> 155     request.send()
    157 if wait:
    158     return request.wait()

File /opt/conda/lib/python3.11/site-packages/snmp/manager/v2c.py:86, in Request.send(self)
     84 now = time.time()
     85 self.nextRefresh = now + self.period
---> 86 self.reallySend()

File /opt/conda/lib/python3.11/site-packages/snmp/manager/v2c.py:62, in Request.reallySend(self)
     61 def reallySend(self):
---> 62     self.manager.sendPdu(self.pdu, self, self.community)

File /opt/conda/lib/python3.11/site-packages/snmp/manager/v2c.py:135, in SNMPv2cManager.sendPdu(self, pdu, handle, community)
    134 def sendPdu(self, pdu, handle, community):
--> 135     self.dispatcher.sendPdu(
    136         self.locator,
    137         MessageProcessingModel.SNMPv2c,
    138         pdu,
    139         handle,
    140         community,
    141     )

File /opt/conda/lib/python3.11/site-packages/snmp/dispatcher.py:87, in Dispatcher.sendPdu(self, locator, mpm, pdu, handle, *args, **kwargs)
     84         mpm = str(MessageProcessingModel(mpm))
     85         raise ValueError("{} is not enabled".format(mpm)) from err
---> 87 msg = mp.prepareOutgoingMessage(pdu, handle, *args, **kwargs)
     88 transport.send(locator.address, msg)

File /opt/conda/lib/python3.11/site-packages/snmp/message/v2c.py:111, in SNMPv2cMessageProcessor.prepareOutgoingMessage(self, pdu, handle, community)
    108     pdu.requestID = self.cache(cacheEntry)
    109     handle.addCallback(self.uncache, pdu.requestID)
--> 111 return Message(self.VERSION, community, pdu).encode()

File /opt/conda/lib/python3.11/site-packages/snmp/types.py:76, in Asn1Encodable.encode(self)
     75 def encode(self) -> bytes:
---> 76     return encode(self.TYPE, self.serialize())

File /opt/conda/lib/python3.11/site-packages/snmp/types.py:499, in Constructed.serialize(self)
    498 def serialize(self) -> bytes:
--> 499     return b"".join([item.encode() for item in self])

File /opt/conda/lib/python3.11/site-packages/snmp/types.py:499, in <listcomp>(.0)
    498 def serialize(self) -> bytes:
--> 499     return b"".join([item.encode() for item in self])

File /opt/conda/lib/python3.11/site-packages/snmp/types.py:76, in Asn1Encodable.encode(self)
     75 def encode(self) -> bytes:
---> 76     return encode(self.TYPE, self.serialize())

File /opt/conda/lib/python3.11/site-packages/snmp/ber.py:281, in encode(identifier, data)
    279 def encode(identifier: Identifier, data: bytes) -> bytes:
    280     """Encode a message under ASN.1 Basic Encoding Rules."""
--> 281     return identifier.encode() + encode_length(len(data)) + data

TypeError: can't concat str to bytes

Do you know how may I solve it or what may cause it?
Thanks!

Bad Community string handling in v2c? and 'get' Timeout

On Windows with Python 3.10

Having a couple of issues, first when I use the v2c "Getting Started" it raises an exception in ber.py, line 273

    return encode_identifier(identifier) + encode_length(len(data)) + data
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can't concat str to bytes

if I change it to a byte string then it just times out

engine = Engine(SNMPv2c, defaultCommunity=config.SNMP_DEFAULT_COMMUNITY.encode('ascii'))
host = engine.Manager(ip_address)
snmp_get = host.get(oid, community=b"default") # added community here to test an invalid one

Exception

.... v2c.py, line 98, in wait
    raise Timeout()
snmp.manager.Timeout

I added a debug line to see how it's encoding the string and this is what I get

b'0(\x02\x01\x01\x04\x07default\xa0\x1a\x02\x04\x95\xfa\xec%\x02\x01\x00\x02\x01\x000\x0c0\n\x06\x06+\x06\x01\x02\x01\x01\x05\x00'

I've tried a valid community string and an invalid one and they both timeout, which tells me it's possibly an issue with the community string but I'm not 100%, might be something really dumb I missed.

Please advise. Thank you.

snmpwalk

Hello Charles! Thanks a lot for your great job!

I'm looking for snmpwalk in the documentation. The library doesn't have this method yet, right?

Garbled hex-string

Hi, using snmp 0.7.1 on vscode on windows 11 I get garbled hex-string occasionally/always... I compare to linux snmpwalk. I read switches, mainly HP, and most snmp data is correct, but MAC adresses and longer hex strings are shortened and garbled. I do

    response = localhost.get(oid)
    var = response.variables[0].value.data

and expect for instance '00:0a:cd:42:2f:24', but get b'\x00\n\xcdA/#'. Is there i fix for this? Thanks

Tutorial not working on Ubuntu

Copy and pasted the tutorial from the readme for using SNMPv3. Receiving a ModuleNotFoundError: No module named 'snmp.openssl'.

What can I do or provide to help with this? I have openssl version 1.1.1f-1ubuntu2.16 installed with apt (and it's the latest version)

Adherence to coding style

Hi, Charles!
This question is not about functionality. It is about following the codestyle. I sincerely wish successful development of your library. Moreover, I am betting on your project to use this library in the future for my work. And I would like to contribute to your project sometimes, if I can offer something interesting.
But there is a problem related to the coding style. If this is the coding style you have chosen intentionally, then this issue can be closed.
But if it's an open issue, then I can suggest you implement some tool like Ruff to keep the coding style strict.
You can also additionally use mypy to check the code for potential typing errors.
What do you think about this?

Example throws exception

Hi mate,

I just copied your example code, substituted hosts with my remote NTCIP machine IP (checkd that it was online first) and ran it.
Here's the result:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\hpavon-e\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\hpavon-e\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\hpavon-e\AppData\Local\Programs\Python\Python37-32\lib\site-packages\snmp\v1\__init__.py", line 58, in _listen_thread
    r, _, _ = select.select([sock, pipe], [], [])
OSError: [WinError 10038] an operation was attempted on something that is not a socket

I guess it's just that being a noob I have missed something. Any help will be much appreciated.

PS: I can get proper response from remote machine executing in command line:
snmpget -v1 -c administrator <my host's IP here> .1.3.6.1.2.1.1.2.0

Not able to install using PIP

Getting this error always

ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them
.
unknown package:
Expected sha256 9b3ae153c89a480a0ec402e23db8d8d84a3833b65fa4b15b81b83be9d637aab9
Got ac81bc994707d6e1542e18ef028cb2c1bf47292188f9572a9f492e0e42fc4b05

Problem when reading some non-existent OIDs

Hi, @charlestolley

I don't know how to formulate the problem more correctly, because I haven't found an explanation for it. Maybe you know what it is about or can help me to understand it.

We have several OLT ZTE C610 instances, which respond to non-existent OIDs with unintelligible data packet. On other instances everything works as it should, but there are some instances where this happens.

In this screenshot, I executed getBulk() once with timeout=4. But in Wireshark I see this response. I can't provide the PCAP itself, as it contains information I can't share publicly.
image
I end up getting a snmp.manager.Timeout exception, although I expect to get something like noSuchName or NoSuchObject or NoSuchInstance. Or just an empty VarBindList().

But, what will Net-SNMP do?
I performed a similar SNMP query using the net-snmp command:

$ snmpbulkwalk -v2c -r1 -t4 10.21.112.82 1.3.6.1.4.1.3902.1015.1010.1.7.4.1.7

And I get the next one, quite an interesting result:
image
Upon receiving this unintelligible response from the SNMP agent, net-snmp performs a snmp-get request to the same OID. And receives a clear noSuchObject in response.
image

Is there any way to replicate this behavior inside getNext(), getBulk() methods?

Test compatibility with macOS

Hi, @charlestolley !

I think I've found a library that at first glance fulfills all my wishes and requirements. And I am very grateful to you!

I'd like to contribute to it in a small way, but before I start, I have to ask if there is some preferred way to propose changes via PR?

Maybe we should first discuss the changes being made before actually making them (for this, it's probably better to activate discussions in the repository).

In any case, some code changes need to be made before I can proceed:

  • the test method uses os.getrandom, which is only available in Linux. Since this is just a test, maybe it would be better to use something more universal?

  • another of the tests was a failure because it uses the snmp.openssl module, which is actually missing (there is only a stub file).

Thanks!

OID increase check

Greetings, @charlestolley!

The getNext and getBulk manager commands do not check for OID increases. Agents that give data out of order can (and most often do) cause a loop.

It is very desirable that such a check be performed by default and an exception thrown if it is detected that the last received OID is not larger than the previous one.

At the same time, there should be an option to forcibly disable this check if necessary, explicitly stating in the documentation that this may cause a loop.

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.