New Upstream Release - python-pysnmp4
Ready changes
Summary
Merged new upstream version: 5.0.21 (was: 5.0.10).
Diff
diff --git a/.github/workflows/agreements.yaml b/.github/workflows/agreements.yaml
deleted file mode 100644
index aad7a93..0000000
--- a/.github/workflows/agreements.yaml
+++ /dev/null
@@ -1,45 +0,0 @@
-name: "CLA Assistant"
-on:
- issue_comment:
- types: [created]
- pull_request_target:
- types: [opened, closed, synchronize]
-
-jobs:
- ContributorLicenseAgreement:
- runs-on: ubuntu-latest
- steps:
- - name: "CLA Assistant"
- if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
- uses: cla-assistant/github-action@v2.1.3-beta
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- PERSONAL_ACCESS_TOKEN: ${{ secrets.PAT_CLATOOL }}
- with:
- path-to-signatures: "signatures/version1/cla.json"
- path-to-document: "https://github.com/splunk/cla-agreement/blob/main/CLA.md" # e.g. a CLA or a DCO document
- branch: "main"
- allowlist: dependabot[bot]
- remote-organization-name: splunk
- remote-repository-name: cla-agreement
- CodeOfConduct:
- runs-on: ubuntu-latest
- steps:
- - name: "COC Assistant"
- if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the Code of Conduct and I hereby accept the Terms') || github.event_name == 'pull_request_target'
- uses: cla-assistant/github-action@v2.1.3-beta
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- PERSONAL_ACCESS_TOKEN: ${{ secrets.PAT_CLATOOL }}
- with:
- path-to-signatures: "signatures/version1/coc.json"
- path-to-document: "https://github.com/splunk/cla-agreement/blob/main/CODE_OF_CONDUCT.md" # e.g. a COC or a DCO document
- branch: "main"
- allowlist: dependabot[bot]
- remote-organization-name: splunk
- remote-repository-name: cla-agreement
- custom-pr-sign-comment: "I have read the Code of Conduct and I hereby accept the Terms"
- create-file-commit-message: "For example: Creating file for storing COC Signatures"
- signed-commit-message: "$contributorName has signed the COC in #$pullRequestNo"
- custom-notsigned-prcomment: "All contributors have NOT signed the COC Document"
- custom-allsigned-prcomment: "****CLA Assistant Lite bot**** All contributors have signed the COC ✍️ ✅"
diff --git a/.github/workflows/build-test-release.yml b/.github/workflows/build-test-release.yml
index 8dab66d..bba7424 100644
--- a/.github/workflows/build-test-release.yml
+++ b/.github/workflows/build-test-release.yml
@@ -74,40 +74,6 @@ jobs:
name: output
path: output
- run-unit-tests:
- name: test-unit
- strategy:
- matrix:
- os: [ubuntu-latest, macos-latest]
- python: ["3.7", "3.8", "3.9"]
- poetry-version: ["1.1.11"]
- fail-fast: false
- runs-on: ${{ matrix.os }}
- needs:
- - build
- steps:
- - uses: actions/checkout@v2
- - name: Setup python
- uses: actions/setup-python@v2
- with:
- python-version: ${{ matrix.python }}
- - name: Run image
- uses: abatilo/actions-poetry@v2.0.0
- with:
- poetry-version: ${{ matrix.poetry-version }}
- - name: run tests
- run: |
- poetry install
- poetry run pytest --junitxml=test-results/results.xml --cov=./ --cov-report=xml tests
- - uses: actions/upload-artifact@v2.2.4
- with:
- name: unit tests test-results
- path: test-results
- - uses: codecov/codecov-action@v2
- with:
- token: ${{ secrets.CODECOV_TOKEN }}
- flags: ${{ matrix.os }}, ${{ matrix.poetry-version }}
- fail_ci_if_error: true # optional (default = false)
publish:
name: Build Release
needs:
@@ -149,7 +115,7 @@ jobs:
@google/semantic-release-replace-plugin
env:
GITHUB_TOKEN: ${{ secrets.SEMREL_TOKEN }}
- PYPI_USERNAME: ${{ secrets.PYPI_USERNAME }}
+ PYPI_USERNAME: "__token__"
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
update-semver:
diff --git a/.github/workflows/sr-release.sh b/.github/workflows/sr-release.sh
index 699a973..66ad37e 100755
--- a/.github/workflows/sr-release.sh
+++ b/.github/workflows/sr-release.sh
@@ -1,6 +1,6 @@
-!/usr/bin/env bash
+#!/usr/bin/env bash
set -eE
set -v
echo pypy user=${PYPI_USERNAME}
-poetry publish -n -u ${PYPI_USERNAME} -p ${PYPI_TOKEN}
+yes | poetry publish --build --username ${PYPI_USERNAME} --password ${PYPI_TOKEN}
diff --git a/.releaserc b/.releaserc
index c1d6333..f4fe12e 100644
--- a/.releaserc
+++ b/.releaserc
@@ -30,8 +30,8 @@
"files": [
"pysnmp/__init__.py"
],
- "from": "__version__ ?=.*",
- "to": "__version__ = \"${nextRelease.version}\"",
+ "from": "__version__ ?= '.*'",
+ "to": "__version__ = '${nextRelease.version}'",
"results": [
{
"file": "pysnmp/__init__.py",
@@ -76,7 +76,7 @@
"assets": [
"NOTICE",
"pyproject.toml",
- "pyasn1/__init__.py"
+ "pysnmp/__init__.py"
],
"message": "chore(release): ${nextRelease.version}\n\n${nextRelease.notes}",
},
diff --git a/README.md b/README.md
index 9723d9f..9831958 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,11 @@
SNMP library for Python
-----------------------
-[![PyPI](https://img.shields.io/pypi/v/pysnmp.svg?maxAge=2592000)](https://pypi.python.org/pypi/pysnmp)
-[![Python Versions](https://img.shields.io/pypi/pyversions/pysnmp.svg)](https://pypi.python.org/pypi/pysnmp/)
-[![Build status](https://travis-ci.org/etingof/pysnmp.svg?branch=master)](https://travis-ci.org/etingof/pysnmp)
-[![GitHub license](https://img.shields.io/badge/license-BSD-blue.svg)](https://raw.githubusercontent.com/etingof/pysnmp/master/LICENSE.rst)
+
+[![PyPI](https://img.shields.io/pypi/v/pysnmplib.svg?maxAge=2592000)](https://pypi.python.org/pypi/pysnmplib)
+[![Python Versions](https://img.shields.io/pypi/pyversions/pysnmplib.svg)](https://pypi.python.org/pypi/pysnmplib/)
+[![CI](https://github.com/pysnmp/pysnmp/actions/workflows/build-test-release.yml/badge.svg)](https://github.com/pysnmp/pysnmp/actions/workflows/build-test-release.yml)
+[![GitHub license](https://img.shields.io/badge/license-BSD-blue.svg)](https://raw.githubusercontent.com/pysnmp/pysnmp/master/LICENSE.rst)
This is a pure-Python, open source and free implementation of v1/v2c/v3
SNMP engine distributed under 2-clause [BSD license](http://snmplabs.com/pysnmp/license.html).
@@ -12,6 +13,8 @@ SNMP engine distributed under 2-clause [BSD license](http://snmplabs.com/pysnmp/
The PySNMP project was initially sponsored by a [PSF](http://www.python.org/psf/) grant.
Thank you!
+This version is a fork of Ilya Etingof's project [etingof/pysnmp](https://github.com/etingof/pysnmp). Ilya sadly passed away on 10-Aug-2022. Announcement [here](https://lists.openstack.org/pipermail/openstack-discuss/2022-August/030062.html). His work is still of great use to the Python community and he will be missed.
+
Features
--------
@@ -43,17 +46,18 @@ Features, specific to SNMPv3 model include:
Download & Install
------------------
-The PySNMP software is freely available for download from [PyPI](https://pypi.python.org/pypi/pysnmp)
-and [GitHub](https://github.com/etingof/pysnmp.git).
+The PySNMP software is freely available for download from [PyPI](https://pypi.python.org/pypi/pysnmplib)
+and [GitHub](https://github.com/pysnmp/pysnmp.git).
Just run:
```bash
-$ pip install pysnmp
+$ pip install pysnmplib
```
-
-to download and install PySNMP along with its dependencies:
+To download and install PySNMP along with its dependencies:
+
+<!-- Need to find an alternate location for the links to snmplabs.com -->
* [PyASN1](http://snmplabs.com/pyasn1/)
* [PyCryptodomex](https://pycryptodome.readthedocs.io) (required only if SNMPv3 encryption is in use)
* [PySMI](http://snmplabs.com/pysmi/) (required for MIB services only)
@@ -64,14 +68,14 @@ written in pure-Python could be installed via:
```bash
$ pip install snmpclitools
```
-
+
and used in the very similar manner as conventional Net-SNMP tools:
```bash
$ 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
--------
@@ -121,9 +125,11 @@ if errorIndication:
print(errorIndication)
```
-We maintain publicly available SNMP Agent and TRAP sink at
-[demo.snmplabs.com](http://snmplabs.com/snmpsim/public-snmp-agent-simulator.html). You are
-welcome to use it while experimenting with whatever SNMP software you deal with.
+> We maintain publicly available SNMP Agent and TRAP sink at
+> [demo.snmplabs.com](http://snmplabs.com/snmpsim/public-snmp-agent-simulator.html). You are
+> welcome to use it while experimenting with whatever SNMP software you deal with.
+
+:warning: ***This is no longer the case as the snmplabs.com site is now defunct***
```bash
$ python3 examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py
@@ -134,25 +140,24 @@ 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](https://pysnmp.github.io/mibs/asn1/)) for that purpose.
-For more example scripts please refer to [examples section](http://snmplabs.com/pysnmp/examples/contents.html#high-level-snmp)
+For more example scripts please refer to ~~[examples section](http://snmplabs.com/pysnmp/examples/contents.html#high-level-snmp)~~
at pysnmp web site.
Documentation
-------------
-Library documentation and examples can be found at the [pysnmp project site](http://snmplabs.com/pysnmp/).
+Library documentation and examples can be found at the ~~[pysnmp project site](http://snmplabs.com/pysnmp/)~~.
If something does not work as expected, please
-[open an issue](https://github.com/etingof/pysnmp/issues) at GitHub or
-post your question [on Stack Overflow](http://stackoverflow.com/questions/ask)
-or try browsing pysnmp
+[open an issue](https://github.com/pysnmp/pysnmp/issues) at GitHub or
+post your question [on Stack Overflow](http://stackoverflow.com/questions/ask) or try browsing pysnmp
[mailing list archives](https://sourceforge.net/p/pysnmp/mailman/pysnmp-users/).
Bug reports and PRs are appreciated! ;-)
-Copyright (c) 2005-2019, [Ilya Etingof](mailto:etingof@gmail.com). All rights reserved.
+Copyright (c) 2005-2019, [Ilya Etingof](https://lists.openstack.org/pipermail/openstack-discuss/2022-August/030062.html). All rights reserved.
diff --git a/debian/changelog b/debian/changelog
index 72d5a1f..f61d657 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,10 +1,14 @@
-python-pysnmp4 (5.0.10-1) UNRELEASED; urgency=medium
+python-pysnmp4 (5.0.21-1) UNRELEASED; urgency=medium
+ [ Luiz Amaral ]
* New upstream release.
* d/watch: Use forked upstream repository
* d/control: Update project Homepage URL
- -- Luiz Amaral <email@luiz.eng.br> Tue, 12 Apr 2022 12:20:10 +0000
+ [ Debian Janitor ]
+ * New upstream release.
+
+ -- Luiz Amaral <email@luiz.eng.br> Sun, 26 Feb 2023 10:26:49 -0000
python-pysnmp4 (4.4.12-2) unstable; urgency=medium
diff --git a/debian/patches/0001-Remove-privacy-breach-badges.patch b/debian/patches/0001-Remove-privacy-breach-badges.patch
index 00193ea..879acb3 100644
--- a/debian/patches/0001-Remove-privacy-breach-badges.patch
+++ b/debian/patches/0001-Remove-privacy-breach-badges.patch
@@ -6,11 +6,11 @@ Subject: Remove privacy-breach badges
docs/source/conf.py | 2 --
1 file changed, 2 deletions(-)
-diff --git a/docs/source/conf.py b/docs/source/conf.py
-index c34a797..8e0ec38 100644
---- a/docs/source/conf.py
-+++ b/docs/source/conf.py
-@@ -122,8 +122,6 @@ html_theme_options = {
+Index: python-pysnmp4.git/docs/source/conf.py
+===================================================================
+--- python-pysnmp4.git.orig/docs/source/conf.py
++++ python-pysnmp4.git/docs/source/conf.py
+@@ -121,8 +121,6 @@ html_theme_options = {
'logo': 'logo.svg',
'description': '<p align=left><i><b>Brewing free software for the greater good</i></b></p>',
'show_powered_by': False,
diff --git a/debian/patches/0002-Reproducible-build.patch b/debian/patches/0002-Reproducible-build.patch
index 68723c8..6233746 100644
--- a/debian/patches/0002-Reproducible-build.patch
+++ b/debian/patches/0002-Reproducible-build.patch
@@ -7,11 +7,11 @@ Last-Update: 2018-01-01
pysnmp/smi/rfc1902.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
-diff --git a/pysnmp/smi/rfc1902.py b/pysnmp/smi/rfc1902.py
-index 87a9d4e..14702ed 100644
---- a/pysnmp/smi/rfc1902.py
-+++ b/pysnmp/smi/rfc1902.py
-@@ -695,7 +695,9 @@ class ObjectType:
+Index: python-pysnmp4.git/pysnmp/smi/rfc1902.py
+===================================================================
+--- python-pysnmp4.git.orig/pysnmp/smi/rfc1902.py
++++ python-pysnmp4.git/pysnmp/smi/rfc1902.py
+@@ -692,7 +692,9 @@ class ObjectType:
"""
stDirty, stClean = 1, 2
diff --git a/docs/source/conf.py b/docs/source/conf.py
index c34a797..fa70b58 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
#
# PySNMP documentation build configuration file, created by
# sphinx-quickstart on Sat Jun 27 23:15:54 2015.
@@ -50,9 +49,9 @@ source_suffix = '.rst'
master_doc = 'contents'
# General information about the project.
-project = u'SNMP library for Python'
-copyright = u'2005-2019, Ilya Etingof <etingof@gmail.com>'
-author = u'Ilya Etingof <etingof@gmail.com>'
+project = 'SNMP library for Python'
+copyright = '2005-2019, Ilya Etingof <etingof@gmail.com>'
+author = 'Ilya Etingof <etingof@gmail.com>'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -245,8 +244,8 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
- (master_doc, 'PySNMP.tex', u'PySNMP Documentation',
- u'Ilya Etingof \\textless{}etingof@gmail.com\\textgreater{}', 'manual'),
+ (master_doc, 'PySNMP.tex', 'PySNMP Documentation',
+ 'Ilya Etingof \\textless{}etingof@gmail.com\\textgreater{}', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -275,7 +274,7 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
- (master_doc, 'pysnmp', u'PySNMP Documentation',
+ (master_doc, 'pysnmp', 'PySNMP Documentation',
[author], 1)
]
@@ -289,7 +288,7 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- (master_doc, 'PySNMP', u'PySNMP Documentation',
+ (master_doc, 'PySNMP', 'PySNMP Documentation',
author, 'PySNMP', 'One line description of project.',
'Miscellaneous'),
]
@@ -312,7 +311,6 @@ intersphinx_mapping = {
'python': ('https://docs.python.org/3.4/', None),
'pyasn1': ('http://snmplabs.com/pyasn1/', None),
'pysmi': ('http://snmplabs.com/pysmi/', None),
- )
}
# this merges constructor docstring with class docstring
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..f88c0ee
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,9 @@
+## Running examples
+
+In order to test pysnmp functionalities, you can run SNMP simulators on your local environment.
+
+One of possible ways to do it is to use [this project](https://github.com/tandrup/docker-snmpsim) to run docker container and map port 161 to the port of your choice, for example:
+
+```commandline
+docker run -d -p 163:161/udp tandrup/snmpsim
+```
\ No newline at end of file
diff --git a/examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py b/examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py
old mode 100644
new mode 100755
index 92d3e70..c70209a
--- a/examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py
+++ b/examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
SNMPv1 TRAP with defaults
+++++++++++++++++++++++++
@@ -17,34 +18,30 @@ using the following options:
Functionally similar to:
-| $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system"
+| $ snmptrap -v1 -c public localhost 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system"
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def run():
+async def run():
snmpEngine = SnmpEngine()
- errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification(
+ errorIndication, errorStatus, errorIndex, varBinds = await sendNotification(
snmpEngine,
- CommunityData('public', mpModel=0),
- UdpTransportTarget(('demo.snmplabs.com', 162)),
+ CommunityData("public", mpModel=0),
+ UdpTransportTarget(("localhost", 161)),
ContextData(),
- 'trap',
- NotificationType(
- ObjectIdentity('1.3.6.1.6.3.1.1.5.2')
- ).addVarBinds(
- ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
- ('1.3.6.1.2.1.1.1.0', OctetString('my system'))
- )
+ "trap",
+ NotificationType(ObjectIdentity("1.3.6.1.6.3.1.1.5.2")).addVarBinds(
+ ("1.3.6.1.6.3.1.1.4.3.0", "1.3.6.1.4.1.20408.4.1.1.2"),
+ ("1.3.6.1.2.1.1.1.0", OctetString("my system")),
+ ),
)
-
if errorIndication:
print(errorIndication)
snmpEngine.transportDispatcher.closeDispatcher()
-asyncio.get_event_loop().run_until_complete(run())
+asyncio.run(run())
diff --git a/examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py b/examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py
old mode 100644
new mode 100755
index 0c5cdba..2c47407
--- a/examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py
+++ b/examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
Multiple concurrent notifications
+++++++++++++++++++++++++++++++++
@@ -18,47 +19,49 @@ what leads to excessive tables information.
Functionally similar to:
-| $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2
-| $ snmpinform -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2
-| $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2
+| $ snmptrap -v2c -c public localhost 12345 1.3.6.1.6.3.1.1.5.2
+| $ snmpinform -v2c -c public localhost 12345 1.3.6.1.6.3.1.1.5.2
+| $ snmptrap -v2c -c public localhost 12345 1.3.6.1.6.3.1.1.5.2
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def sendone(snmpEngine, hostname, notifyType):
- (errorIndication,
- errorStatus,
- errorIndex,
- varBinds) = yield from sendNotification(
+async def sendone(snmpEngine, hostname, notifyType):
+ (errorIndication, errorStatus, errorIndex, varBinds) = await sendNotification(
snmpEngine,
- CommunityData('public', tag=hostname),
+ CommunityData("public", tag=hostname),
UdpTransportTarget((hostname, 162), tagList=hostname),
ContextData(),
notifyType,
- NotificationType(
- ObjectIdentity('1.3.6.1.6.3.1.1.5.2')
- ).addVarBinds(
- ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
- ('1.3.6.1.2.1.1.1.0', OctetString('my system'))
- )
+ NotificationType(ObjectIdentity("1.3.6.1.6.3.1.1.6.1.0")).addVarBinds(
+ ("1.3.6.1.2.1.1.1.0", OctetString("my system"))
+ ),
)
if errorIndication:
- print(errorIndication)
+ print(f"{notifyType}: {errorIndication}")
elif errorStatus:
- print('{}: at {}'.format(errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{}: at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for varBind in varBinds:
- print(' = '.join([x.prettyPrint() for x in varBind]))
+ print(" = ".join([x.prettyPrint() for x in varBind]))
snmpEngine = SnmpEngine()
-loop = asyncio.get_event_loop()
-loop.run_until_complete(
- asyncio.wait([sendone(snmpEngine, 'demo.snmplabs.com', 'trap'),
- sendone(snmpEngine, 'demo.snmplabs.com', 'inform')])
-)
+
+async def main():
+ await asyncio.gather(
+ sendone(snmpEngine, "localhost", "trap"),
+ sendone(snmpEngine, "localhost", "inform"),
+ )
+
+
+asyncio.run(main())
diff --git a/examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py b/examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py
old mode 100644
new mode 100755
index 05a4ca8..b91d364
--- a/examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py
+++ b/examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
Bulk walk MIB
+++++++++++++
@@ -6,58 +7,54 @@ Send a series of SNMP GETBULK requests using the following options:
* with SNMPv3, user 'usr-none-none', no authentication, no privacy
* over IPv4/UDP
-* to an Agent at demo.snmplabs.com:161
+* to an Agent at localhost:161
* for all OIDs past SNMPv2-MIB::system
* run till end-of-mib condition is reported by Agent
* based on asyncio I/O framework
Functionally similar to:
-| $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 \
-| demo.snmplabs.com SNMPv2-MIB::system
+| $ snmpbulkwalk -v3 -lnoAuthNoPriv -u public -Cn0 -Cr50 \
+| localhost SNMPv2-MIB::system
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def run(varBinds):
+async def run(varBinds):
snmpEngine = SnmpEngine()
while True:
- (errorIndication,
- errorStatus,
- errorIndex,
- varBindTable) = yield from bulkCmd(
+ errorIndication, errorStatus, errorIndex, varBindTable = await bulkCmd(
snmpEngine,
- UsmUserData('usr-none-none'),
- UdpTransportTarget(('demo.snmplabs.com', 161)),
+ CommunityData("public"),
+ UdpTransportTarget(("localhost", 161)),
ContextData(),
- 0, 50,
- *varBinds)
-
+ 0,
+ 50,
+ *varBinds
+ )
if errorIndication:
print(errorIndication)
break
elif errorStatus:
- print('{} at {}'.format(
- errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
)
- )
else:
for varBindRow in varBindTable:
for varBind in varBindRow:
- print(' = '.join([x.prettyPrint() for x in varBind]))
+ print(" = ".join([x.prettyPrint() for x in varBind]))
varBinds = varBindTable[-1]
if isEndOfMib(varBinds):
break
-
- snmpEngine.transportDispatcher.closeDispatcher()
+ return
-loop = asyncio.get_event_loop()
-loop.run_until_complete(
- run([ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))])
+asyncio.run(
+ run([ObjectType(ObjectIdentity("TCP-MIB")), ObjectType(ObjectIdentity("IP-MIB"))])
)
diff --git a/examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py b/examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py
old mode 100644
new mode 100755
index 974b456..21b99d3
--- a/examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py
+++ b/examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
Concurrent queries
++++++++++++++++++
@@ -6,49 +7,53 @@ Send multiple SNMP GET requests at once using the following options:
* with SNMPv2c, community 'public'
* over IPv4/UDP
-* to multiple Agents at demo.snmplabs.com
+* to multiple Agents at localhost
* for instance of SNMPv2-MIB::sysDescr.0 MIB object
* based on asyncio I/O framework
Functionally similar to:
-| $ snmpget -v2c -c public demo.snmplabs.com:1161 SNMPv2-MIB::sysDescr.0
-| $ snmpget -v2c -c public demo.snmplabs.com:2161 SNMPv2-MIB::sysDescr.0
-| $ snmpget -v2c -c public demo.snmplabs.com:3161 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:161 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:162 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:163 SNMPv2-MIB::sysDescr.0
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def getone(snmpEngine, hostname):
- errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
+async def getone(snmpEngine, hostname):
+ errorIndication, errorStatus, errorIndex, varBinds = await getCmd(
snmpEngine,
- CommunityData('public'),
+ CommunityData("public"),
UdpTransportTarget(hostname),
ContextData(),
- ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
+ ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
)
if errorIndication:
- print(errorIndication)
+ print(f'{hostname}: {errorIndication}')
elif errorStatus:
- print('{} at {}'.format(
- errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
)
- )
else:
for varBind in varBinds:
- print(' = '.join([x.prettyPrint() for x in varBind]))
+ print(" = ".join([x.prettyPrint() for x in varBind]))
snmpEngine = SnmpEngine()
-loop = asyncio.get_event_loop()
-loop.run_until_complete(
- asyncio.wait([getone(snmpEngine, ('demo.snmplabs.com', 1161)),
- getone(snmpEngine, ('demo.snmplabs.com', 2161)),
- getone(snmpEngine, ('demo.snmplabs.com', 3161))])
-)
+
+async def main():
+ await asyncio.gather(
+ getone(snmpEngine, ("localhost", 161)),
+ getone(snmpEngine, ("localhost6", 161)),
+ getone(snmpEngine, ("localhost", 163)),
+ )
+
+
+asyncio.run(main())
diff --git a/examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py b/examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py
old mode 100644
new mode 100755
index a68a290..aab182b
--- a/examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py
+++ b/examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
Sequential queries
++++++++++++++++++
@@ -6,53 +7,51 @@ Send multiple SNMP GET requests one by one using the following options:
* with SNMPv2c, community 'public'
* over IPv4/UDP
-* to multiple Agents at demo.snmplabs.com
+* to multiple Agents at localhost
* for instance of SNMPv2-MIB::sysDescr.0 MIB object
* based on asyncio I/O framework
Functionally similar to:
-| $ snmpget -v2c -c public demo.snmplabs.com:1161 SNMPv2-MIB::sysDescr.0
-| $ snmpget -v2c -c public demo.snmplabs.com:2161 SNMPv2-MIB::sysDescr.0
-| $ snmpget -v2c -c public demo.snmplabs.com:3161 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:161 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:162 SNMPv2-MIB::sysDescr.0
+| $ snmpget -v2c -c public localhost:163 SNMPv2-MIB::sysDescr.0
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def getone(snmpEngine, hostname):
- errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
+async def getone(snmpEngine, hostname):
+ errorIndication, errorStatus, errorIndex, varBinds = await getCmd(
snmpEngine,
- CommunityData('public'),
+ CommunityData("public"),
UdpTransportTarget(hostname),
ContextData(),
- ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
+ ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
)
if errorIndication:
- print(errorIndication)
+ print(f'{hostname}: {errorIndication}')
elif errorStatus:
- print('{} at {}'.format(
- errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
)
- )
else:
for varBind in varBinds:
- print(' = '.join([x.prettyPrint() for x in varBind]))
+ print(" = ".join([x.prettyPrint() for x in varBind]))
-@asyncio.coroutine
-def getall(snmpEngine, hostnames):
+async def getall(snmpEngine, hostnames):
for hostname in hostnames:
- yield from getone(snmpEngine, hostname)
+ await 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)]))
+asyncio.run(
+ getall(snmpEngine, [("localhost", 161), ("localhost6", 161), ("localhost", 163)])
+)
diff --git a/examples/hlapi/asyncio/manager/cmdgen/v1-get.py b/examples/hlapi/asyncio/manager/cmdgen/v1-get.py
old mode 100644
new mode 100755
index b4cde91..de5e02e
--- a/examples/hlapi/asyncio/manager/cmdgen/v1-get.py
+++ b/examples/hlapi/asyncio/manager/cmdgen/v1-get.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
"""
SNMPv1
++++++
@@ -6,43 +7,43 @@ Send SNMP GET request using the following options:
* with SNMPv1, community 'public'
* over IPv4/UDP
- * to an Agent at demo.snmplabs.com:161
+ * to an Agent at localhost:161
* for an instance of SNMPv2-MIB::sysDescr.0 MIB object
* Based on asyncio I/O framework
Functionally similar to:
-| $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0
+| $ snmpget -v1 -c public localhost SNMPv2-MIB::sysDescr.0
-"""#
+""" #
import asyncio
from pysnmp.hlapi.asyncio import *
-@asyncio.coroutine
-def run():
+async def run():
snmpEngine = SnmpEngine()
- errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
+ errorIndication, errorStatus, errorIndex, varBinds = await getCmd(
snmpEngine,
- CommunityData('public', mpModel=0),
- UdpTransportTarget(('demo.snmplabs.com', 161)),
+ CommunityData("public", mpModel=0),
+ UdpTransportTarget(("localhost", 161)),
ContextData(),
- ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
+ ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
)
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(
- errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
)
- )
else:
for varBind in varBinds:
- print(' = '.join([x.prettyPrint() for x in varBind]))
+ print(" = ".join([x.prettyPrint() for x in varBind]))
snmpEngine.transportDispatcher.closeDispatcher()
-asyncio.get_event_loop().run_until_complete(run())
+asyncio.run(run())
diff --git a/examples/smi/agent/custom-managed-object.py b/examples/smi/agent/custom-managed-object.py
index 0b17519..75d26b2 100644
--- a/examples/smi/agent/custom-managed-object.py
+++ b/examples/smi/agent/custom-managed-object.py
@@ -5,7 +5,7 @@ Implementing MIB objects
This script explains how SNMP Agent application could model
real-world data as Managed Objects defined in MIB.
-"""#
+""" #
from pysnmp.smi import builder
# MIB Builder is normally pre-created by SNMP engine
@@ -17,12 +17,10 @@ mibBuilder = builder.MibBuilder()
#
# A base class for a custom Managed Object
-MibScalarInstance, = mibBuilder.importSymbols(
- 'SNMPv2-SMI', 'MibScalarInstance'
-)
+(MibScalarInstance,) = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalarInstance")
# Managed object specification
-sysLocation, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysLocation')
+(sysLocation,) = mibBuilder.importSymbols("SNMPv2-MIB", "sysLocation")
# Custom Managed Object
@@ -30,20 +28,19 @@ class MySysLocationInstance(MibScalarInstance):
# noinspection PyUnusedLocal
def readGet(self, name, *args):
# Just return a custom value
- return name, self.syntax.clone('The Leaky Cauldron')
+ return name, self.syntax.clone("The Leaky Cauldron")
-sysLocationInstance = MySysLocationInstance(
- sysLocation.name, (0,), sysLocation.syntax
-)
+sysLocationInstance = MySysLocationInstance(sysLocation.name, (0,), sysLocation.syntax)
# Register Managed Object with a MIB tree
mibBuilder.exportSymbols(
# '__' prefixed MIB modules take precedence on indexing
- '__MY-LOCATION-MIB', sysLocationInstance=sysLocationInstance
+ "__MY-LOCATION-MIB",
+ sysLocationInstance=sysLocationInstance,
)
-if __name__ == '__main__':
+if __name__ == "__main__":
#
# This is what is done internally by Agent.
#
@@ -51,7 +48,7 @@ if __name__ == '__main__':
mibInstrum = instrum.MibInstrumController(mibBuilder)
- print('Remote manager read access to MIB instrumentation (table walk)')
+ print("Remote manager read access to MIB instrumentation (table walk)")
oid, val = (), None
while 1:
oid, val = mibInstrum.readNextVars(((oid, val),))[0]
diff --git a/examples/smi/agent/operations-on-managed-objects.py b/examples/smi/agent/operations-on-managed-objects.py
index e4e5cc8..61e4d8e 100644
--- a/examples/smi/agent/operations-on-managed-objects.py
+++ b/examples/smi/agent/operations-on-managed-objects.py
@@ -5,46 +5,58 @@ Agent operations on MIB
This script explains how SNMP Agent application manipulates
its MIB possibly triggered by SNMP Manager's commands.
-"""#
+""" #
# SNMP agent backend e.g. Agent access to Managed Objects
from pysnmp.smi import builder, instrum, exval
-print('Loading MIB modules...'),
+print("Loading MIB modules..."),
mibBuilder = builder.MibBuilder().loadModules(
- 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB'
+ "SNMPv2-MIB", "SNMP-FRAMEWORK-MIB", "SNMP-COMMUNITY-MIB"
)
-print('done')
+print("done")
-print('Building MIB tree...'),
+print("Building MIB tree..."),
mibInstrum = instrum.MibInstrumController(mibBuilder)
-print('done')
+print("done")
-print('Building table entry index from human-friendly representation...'),
-snmpCommunityEntry, = mibBuilder.importSymbols(
- 'SNMP-COMMUNITY-MIB', 'snmpCommunityEntry'
+print("Building table entry index from human-friendly representation..."),
+(snmpCommunityEntry,) = mibBuilder.importSymbols(
+ "SNMP-COMMUNITY-MIB", "snmpCommunityEntry"
)
-instanceId = snmpCommunityEntry.getInstIdFromIndices('my-router')
-print('done')
+instanceId = snmpCommunityEntry.getInstIdFromIndices("my-router")
+print("done")
-print('Create/update SNMP-COMMUNITY-MIB::snmpCommunityEntry table row: ')
+print("Create/update SNMP-COMMUNITY-MIB::snmpCommunityEntry table row: ")
varBinds = mibInstrum.writeVars(
- ((snmpCommunityEntry.name + (2,) + instanceId, 'mycomm'),
- (snmpCommunityEntry.name + (3,) + instanceId, 'mynmsname'),
- (snmpCommunityEntry.name + (7,) + instanceId, 'volatile'))
+ (
+ (snmpCommunityEntry.name + (2,) + instanceId, "mycomm"),
+ (snmpCommunityEntry.name + (3,) + instanceId, "mynmsname"),
+ (snmpCommunityEntry.name + (7,) + instanceId, "volatile"),
+ )
)
for oid, val in varBinds:
- print('{} = {}'.format('.'.join([str(x) for x in oid]), not val.isValue and 'N/A' or val.prettyPrint()))
-print('done')
-
-print('Read whole MIB (table walk)')
+ print(
+ "{} = {}".format(
+ ".".join([str(x) for x in oid]),
+ not val.isValue and "N/A" or val.prettyPrint(),
+ )
+ )
+print("done")
+
+print("Read whole MIB (table walk)")
oid, val = (), None
while True:
oid, val = mibInstrum.readNextVars(((oid, val),))[0]
if exval.endOfMib.isSameTypeWith(val):
break
- print('{} = {}'.format('.'.join([str(x) for x in oid]), not val.isValue and 'N/A' or val.prettyPrint()))
-print('done')
-
-print('Unloading MIB modules...'),
+ print(
+ "{} = {}".format(
+ ".".join([str(x) for x in oid]),
+ not val.isValue and "N/A" or val.prettyPrint(),
+ )
+ )
+print("done")
+
+print("Unloading MIB modules..."),
mibBuilder.unloadModules()
-print('done')
+print("done")
diff --git a/examples/smi/manager/builder.py b/examples/smi/manager/builder.py
index 369524b..d3f26c0 100644
--- a/examples/smi/manager/builder.py
+++ b/examples/smi/manager/builder.py
@@ -26,10 +26,8 @@ except ImportError:
import imp
PY_MAGIC_NUMBER = imp.get_magic()
- SOURCE_SUFFIXES = [s[0] for s in imp.get_suffixes()
- if s[2] == imp.PY_SOURCE]
- BYTECODE_SUFFIXES = [s[0] for s in imp.get_suffixes()
- if s[2] == imp.PY_COMPILED]
+ SOURCE_SUFFIXES = [s[0] for s in imp.get_suffixes() if s[2] == imp.PY_SOURCE]
+ BYTECODE_SUFFIXES = [s[0] for s in imp.get_suffixes() if s[2] == imp.PY_COMPILED]
PY_SUFFIXES = SOURCE_SUFFIXES + BYTECODE_SUFFIXES
@@ -54,26 +52,26 @@ class __AbstractMibSource:
def __init__(self, srcName):
self._srcName = srcName
self.__inited = None
- debug.logger & debug.flagBld and debug.logger('trying %s' % self)
+ debug.logger & debug.flagBld and debug.logger("trying %s" % self)
def __repr__(self):
- return f'{self.__class__.__name__}({self._srcName!r})'
+ return f"{self.__class__.__name__}({self._srcName!r})"
def _uniqNames(self, files):
u = set()
for f in files:
- if f.startswith('__init__.'):
+ if f.startswith("__init__."):
continue
- u.update(f[:-len(sfx)] for sfx in PY_SUFFIXES if f.endswith(sfx))
+ u.update(f[: -len(sfx)] for sfx in PY_SUFFIXES if f.endswith(sfx))
return tuple(u)
# MibSource API follows
- def fullPath(self, f='', sfx=''):
- return self._srcName + (f and (os.sep + f + sfx) or '')
+ def fullPath(self, f="", sfx=""):
+ return self._srcName + (f and (os.sep + f + sfx) or "")
def init(self):
if self.__inited is None:
@@ -95,30 +93,34 @@ class __AbstractMibSource:
for pycSfx in BYTECODE_SUFFIXES:
try:
- pycData, pycPath = self._getData(f + pycSfx, 'rb')
+ pycData, pycPath = self._getData(f + pycSfx, "rb")
except OSError:
why = sys.exc_info()[1]
if ENOENT == -1 or why.errno == ENOENT:
debug.logger & debug.flagBld and debug.logger(
- f'file {f + pycSfx} access error: {why}'
+ f"file {f + pycSfx} access error: {why}"
)
else:
- raise error.MibLoadError(f'MIB file {f + pycSfx} access error: {why}')
+ raise error.MibLoadError(
+ f"MIB file {f + pycSfx} access error: {why}"
+ )
else:
if PY_MAGIC_NUMBER == pycData[:4]:
pycData = pycData[4:]
- pycTime = struct.unpack('<L', pycData[:4])[0]
+ pycTime = struct.unpack("<L", pycData[:4])[0]
pycData = pycData[4:]
debug.logger & debug.flagBld and debug.logger(
- 'file %s mtime %d' % (pycPath, pycTime)
+ "file %s mtime %d" % (pycPath, pycTime)
)
break
else:
- debug.logger & debug.flagBld and debug.logger('bad magic in %s' % pycPath)
+ debug.logger & debug.flagBld and debug.logger(
+ "bad magic in %s" % pycPath
+ )
for pySfx in SOURCE_SUFFIXES:
@@ -129,24 +131,28 @@ class __AbstractMibSource:
why = sys.exc_info()[1]
if ENOENT == -1 or why.errno == ENOENT:
debug.logger & debug.flagBld and debug.logger(
- f'file {f + pySfx} access error: {why}'
+ f"file {f + pySfx} access error: {why}"
)
else:
- raise error.MibLoadError(f'MIB file {f + pySfx} access error: {why}')
+ raise error.MibLoadError(
+ f"MIB file {f + pySfx} access error: {why}"
+ )
else:
- debug.logger & debug.flagBld and debug.logger('file %s mtime %d' % (f + pySfx, pyTime))
+ debug.logger & debug.flagBld and debug.logger(
+ "file %s mtime %d" % (f + pySfx, pyTime)
+ )
break
if pycTime != -1 and pycTime >= pyTime:
return marshal.loads(pycData), pycSfx
if pyTime != -1:
- modData, pyPath = self._getData(f + pySfx, 'r')
- return compile(modData, pyPath, 'exec'), pyPath
+ modData, pyPath = self._getData(f + pySfx, "r")
+ return compile(modData, pyPath, "exec"), pyPath
- raise OSError(ENOENT, 'No suitable module found', f)
+ raise OSError(ENOENT, "No suitable module found", f)
# Interfaces for subclasses
def _init(self):
@@ -165,16 +171,16 @@ class __AbstractMibSource:
class ZipMibSource(__AbstractMibSource):
def _init(self):
try:
- p = __import__(self._srcName, globals(), locals(), ['__init__'])
- if hasattr(p, '__loader__') and hasattr(p.__loader__, '_files'):
+ p = __import__(self._srcName, globals(), locals(), ["__init__"])
+ if hasattr(p, "__loader__") and hasattr(p.__loader__, "_files"):
self.__loader = p.__loader__
- self._srcName = self._srcName.replace('.', os.sep)
+ self._srcName = self._srcName.replace(".", os.sep)
return self
- elif hasattr(p, '__file__'):
+ elif hasattr(p, "__file__"):
# Dir relative to PYTHONPATH
return DirMibSource(os.path.split(p.__file__)[0]).init()
else:
- raise error.MibLoadError(f'{p} access error')
+ raise error.MibLoadError(f"{p} access error")
except ImportError:
# Dir relative to CWD
@@ -182,15 +188,17 @@ class ZipMibSource(__AbstractMibSource):
@staticmethod
def _parseDosTime(dosdate, dostime):
- t = (((dosdate >> 9) & 0x7f) + 1980, # year
- ((dosdate >> 5) & 0x0f), # month
- dosdate & 0x1f, # mday
- (dostime >> 11) & 0x1f, # hour
- (dostime >> 5) & 0x3f, # min
- (dostime & 0x1f) * 2, # sec
- -1, # wday
- -1, # yday
- -1) # dst
+ t = (
+ ((dosdate >> 9) & 0x7F) + 1980, # year
+ ((dosdate >> 5) & 0x0F), # month
+ dosdate & 0x1F, # mday
+ (dostime >> 11) & 0x1F, # hour
+ (dostime >> 5) & 0x3F, # min
+ (dostime & 0x1F) * 2, # sec
+ -1, # wday
+ -1, # yday
+ -1,
+ ) # dst
return time.mktime(t)
def _listdir(self):
@@ -211,7 +219,7 @@ class ZipMibSource(__AbstractMibSource):
self.__loader._files[p][6], self.__loader._files[p][5]
)
else:
- raise OSError(ENOENT, 'No such file in ZIP archive', p)
+ raise OSError(ENOENT, "No such file in ZIP archive", p)
def _getData(self, f, mode=None):
p = os.path.join(self._srcName, f)
@@ -220,7 +228,7 @@ class ZipMibSource(__AbstractMibSource):
except Exception: # ZIP code seems to return all kinds of errors
why = sys.exc_info()
- raise OSError(ENOENT, f'File or ZIP archive {p} access error: {why[1]}')
+ raise OSError(ENOENT, f"File or ZIP archive {p} access error: {why[1]}")
class DirMibSource(__AbstractMibSource):
@@ -234,7 +242,8 @@ class DirMibSource(__AbstractMibSource):
except OSError:
why = sys.exc_info()
debug.logger & debug.flagBld and debug.logger(
- f'listdir() failed for {self._srcName}: {why[1]}')
+ f"listdir() failed for {self._srcName}: {why[1]}"
+ )
return ()
def _getTimestamp(self, f):
@@ -242,10 +251,10 @@ class DirMibSource(__AbstractMibSource):
try:
return os.stat(p)[8]
except OSError:
- raise OSError(ENOENT, 'No such file: %s' % sys.exc_info()[1], p)
+ raise OSError(ENOENT, "No such file: %s" % sys.exc_info()[1], p)
def _getData(self, f, mode):
- p = os.path.join(self._srcName, '*')
+ p = os.path.join(self._srcName, "*")
try:
if f in os.listdir(self._srcName): # make FS case-sensitive
p = os.path.join(self._srcName, f)
@@ -256,20 +265,19 @@ class DirMibSource(__AbstractMibSource):
except OSError:
why = sys.exc_info()
- msg = f'File or directory {p} access error: {why[1]}'
+ msg = f"File or directory {p} access error: {why[1]}"
else:
- msg = 'No such file or directory: %s' % p
+ msg = "No such file or directory: %s" % p
raise OSError(ENOENT, msg)
+
class MibBuilder:
- defaultCoreMibs = os.pathsep.join(
- ('pysnmp.smi.mibs.instances', 'pysnmp.smi.mibs')
- )
- defaultMiscMibs = 'pysnmp_mibs'
+ defaultCoreMibs = os.pathsep.join(("pysnmp.smi.mibs.instances", "pysnmp.smi.mibs"))
+ defaultMiscMibs = "pysnmp_mibs"
- moduleID = 'PYSNMP_MODULE_ID'
+ moduleID = "PYSNMP_MODULE_ID"
loadTexts = False
@@ -279,7 +287,7 @@ class MibBuilder:
def __init__(self):
self.lastBuildId = self._autoName = 0
sources = []
- for ev in 'PYSNMP_MIB_PKGS', 'PYSNMP_MIB_DIRS', 'PYSNMP_MIB_DIR':
+ for ev in "PYSNMP_MIB_PKGS", "PYSNMP_MIB_DIRS", "PYSNMP_MIB_DIR":
if ev in os.environ:
for m in os.environ[ev].split(os.pathsep):
sources.append(ZipMibSource(m))
@@ -309,11 +317,15 @@ class MibBuilder:
def addMibSources(self, *mibSources):
self.__mibSources.extend([s.init() for s in mibSources])
- debug.logger & debug.flagBld and debug.logger(f'addMibSources: new MIB sources {self.__mibSources}')
+ debug.logger & debug.flagBld and debug.logger(
+ f"addMibSources: new MIB sources {self.__mibSources}"
+ )
def setMibSources(self, *mibSources):
self.__mibSources = [s.init() for s in mibSources]
- debug.logger & debug.flagBld and debug.logger(f'setMibSources: new MIB sources {self.__mibSources}')
+ debug.logger & debug.flagBld and debug.logger(
+ f"setMibSources: new MIB sources {self.__mibSources}"
+ )
def getMibSources(self):
return tuple(self.__mibSources)
@@ -329,34 +341,41 @@ class MibBuilder:
paths += (mibSource.fullPath(),)
else:
raise error.MibLoadError(
- f'MIB source is not a plain directory: {mibSource}'
+ f"MIB source is not a plain directory: {mibSource}"
)
return paths
def loadModule(self, modName, **userCtx):
"""Load and execute MIB modules as Python code"""
for mibSource in self.__mibSources:
- debug.logger & debug.flagBld and debug.logger(f'loadModule: trying {modName} at {mibSource}')
+ debug.logger & debug.flagBld and debug.logger(
+ f"loadModule: trying {modName} at {mibSource}"
+ )
try:
codeObj, sfx = mibSource.read(modName)
except OSError:
debug.logger & debug.flagBld and debug.logger(
- f'loadModule: read {modName} from {mibSource} failed: {sys.exc_info()[1]}')
+ f"loadModule: read {modName} from {mibSource} failed: {sys.exc_info()[1]}"
+ )
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self.__modPathsSeen:
- debug.logger & debug.flagBld and debug.logger('loadModule: seen %s' % modPath)
+ debug.logger & debug.flagBld and debug.logger(
+ "loadModule: seen %s" % modPath
+ )
break
else:
self.__modPathsSeen.add(modPath)
- debug.logger & debug.flagBld and debug.logger('loadModule: evaluating %s' % modPath)
+ debug.logger & debug.flagBld and debug.logger(
+ "loadModule: evaluating %s" % modPath
+ )
- g = {'mibBuilder': self, 'userCtx': userCtx}
+ g = {"mibBuilder": self, "userCtx": userCtx}
try:
exec(codeObj, g)
@@ -364,19 +383,23 @@ class MibBuilder:
except Exception:
self.__modPathsSeen.remove(modPath)
raise error.MibLoadError(
- f'MIB module \'{modPath}\' load error: {traceback.format_exception(*sys.exc_info())}'
+ f"MIB module '{modPath}' load error: {traceback.format_exception(*sys.exc_info())}"
)
self.__modSeen[modName] = modPath
- debug.logger & debug.flagBld and debug.logger('loadModule: loaded %s' % modPath)
+ debug.logger & debug.flagBld and debug.logger(
+ "loadModule: loaded %s" % modPath
+ )
break
if modName not in self.__modSeen:
raise error.MibNotFoundError(
- 'MIB file \"{}\" not found in search path ({})'.format(
- modName and modName + ".py[co]", ', '.join([str(x) for x in self.__mibSources]))
+ 'MIB file "{}" not found in search path ({})'.format(
+ modName and modName + ".py[co]",
+ ", ".join([str(x) for x in self.__mibSources]),
+ )
)
return self
@@ -392,9 +415,7 @@ class MibBuilder:
modNames = list(modNames)
if not modNames:
- raise error.MibNotFoundError(
- f'No MIB module to load at {self}'
- )
+ raise error.MibNotFoundError(f"No MIB module to load at {self}")
for modName in modNames:
try:
@@ -402,12 +423,23 @@ class MibBuilder:
except error.MibNotFoundError:
if self.__mibCompiler:
- debug.logger & debug.flagBld and debug.logger('loadModules: calling MIB compiler for %s' % modName)
- status = self.__mibCompiler.compile(modName, genTexts=self.loadTexts)
- errs = '; '.join([hasattr(x, 'error') and str(x.error) or x for x in status.values() if
- x in ('failed', 'missing')])
+ debug.logger & debug.flagBld and debug.logger(
+ "loadModules: calling MIB compiler for %s" % modName
+ )
+ status = self.__mibCompiler.compile(
+ modName, genTexts=self.loadTexts
+ )
+ errs = "; ".join(
+ [
+ hasattr(x, "error") and str(x.error) or x
+ for x in status.values()
+ if x in ("failed", "missing")
+ ]
+ )
if errs:
- raise error.MibNotFoundError(f'{modName} compilation error(s): {errs}')
+ raise error.MibNotFoundError(
+ f"{modName} compilation error(s): {errs}"
+ )
# compilation succeeded, MIB might load now
self.loadModule(modName, **userCtx)
@@ -419,34 +451,26 @@ class MibBuilder:
modNames = list(self.mibSymbols.keys())
for modName in modNames:
if modName not in self.mibSymbols:
- raise error.MibNotFoundError(
- f'No module {modName} at {self}'
- )
+ raise error.MibNotFoundError(f"No module {modName} at {self}")
self.unexportSymbols(modName)
self.__modPathsSeen.remove(self.__modSeen[modName])
del self.__modSeen[modName]
- debug.logger & debug.flagBld and debug.logger('unloadModules: %s' % modName)
+ debug.logger & debug.flagBld and debug.logger("unloadModules: %s" % modName)
return self
def importSymbols(self, modName, *symNames, **userCtx):
if not modName:
- raise error.SmiError(
- 'importSymbols: empty MIB module name'
- )
+ raise error.SmiError("importSymbols: empty MIB module name")
r = ()
for symName in symNames:
if modName not in self.mibSymbols:
self.loadModules(modName, **userCtx)
if modName not in self.mibSymbols:
- raise error.MibNotFoundError(
- f'No module {modName} loaded at {self}'
- )
+ raise error.MibNotFoundError(f"No module {modName} loaded at {self}")
if symName not in self.mibSymbols[modName]:
- raise error.SmiError(
- f'No symbol {modName}::{symName} at {self}'
- )
+ raise error.SmiError(f"No symbol {modName}::{symName} at {self}")
r = r + (self.mibSymbols[modName][symName],)
return r
@@ -457,17 +481,16 @@ class MibBuilder:
for symObj in anonymousSyms:
debug.logger & debug.flagBld and debug.logger(
- 'exportSymbols: anonymous symbol %s::__pysnmp_%ld' % (modName, self._autoName))
- mibSymbols['__pysnmp_%ld' % self._autoName] = symObj
+ "exportSymbols: anonymous symbol %s::__pysnmp_%ld"
+ % (modName, self._autoName)
+ )
+ mibSymbols["__pysnmp_%ld" % self._autoName] = symObj
self._autoName += 1
for symName, symObj in namedSyms.items():
if symName in mibSymbols:
- raise error.SmiError(
- f'Symbol {symName} already exported at {modName}'
- )
+ raise error.SmiError(f"Symbol {symName} already exported at {modName}")
- if symName != self.moduleID and \
- not isinstance(symObj, classTypes):
+ if symName != self.moduleID and not isinstance(symObj, classTypes):
label = symObj.getLabel()
if label:
symName = label
@@ -476,24 +499,26 @@ class MibBuilder:
mibSymbols[symName] = symObj
- debug.logger & debug.flagBld and debug.logger(f'exportSymbols: symbol {modName}::{symName}')
+ debug.logger & debug.flagBld and debug.logger(
+ f"exportSymbols: symbol {modName}::{symName}"
+ )
self.lastBuildId += 1
def unexportSymbols(self, modName, *symNames):
if modName not in self.mibSymbols:
- raise error.SmiError(f'No module {modName} at {self}')
+ raise error.SmiError(f"No module {modName} at {self}")
mibSymbols = self.mibSymbols[modName]
if not symNames:
symNames = list(mibSymbols.keys())
for symName in symNames:
if symName not in mibSymbols:
- raise error.SmiError(
- f'No symbol {modName}::{symName} at {self}'
- )
+ raise error.SmiError(f"No symbol {modName}::{symName} at {self}")
del mibSymbols[symName]
- debug.logger & debug.flagBld and debug.logger(f'unexportSymbols: symbol {modName}::{symName}')
+ debug.logger & debug.flagBld and debug.logger(
+ f"unexportSymbols: symbol {modName}::{symName}"
+ )
if not self.mibSymbols[modName]:
del self.mibSymbols[modName]
diff --git a/examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py b/examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py
index 55800b0..cd198bb 100644
--- a/examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py
+++ b/examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py
@@ -7,31 +7,38 @@ variable-bindings into MIB objects or the other way around.
The code that configures MIB compiler is similar to what
happens inside the pysnmp.hlapi API.
-"""#
+""" #
from pysnmp.smi import builder, view, compiler, rfc1902
# Assemble MIB browser
mibBuilder = builder.MibBuilder()
mibViewController = view.MibViewController(mibBuilder)
-compiler.addMibCompiler(mibBuilder, sources=['file:///usr/share/snmp/mibs',
- 'https://pysnmp.github.io/mibs/asn1/@mib@'])
+compiler.addMibCompiler(
+ mibBuilder,
+ sources=["file:///usr/share/snmp/mibs", "https://pysnmp.github.io/mibs/asn1/@mib@"],
+)
# Pre-load MIB modules we expect to work with
-mibBuilder.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB')
+mibBuilder.loadModules("SNMPv2-MIB", "SNMP-COMMUNITY-MIB")
# This is what we can get in TRAP PDU
varBinds = [
- ('1.3.6.1.2.1.1.3.0', 12345),
- ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.6.3.1.1.5.2'),
- ('1.3.6.1.6.3.18.1.3.0', '0.0.0.0'),
- ('1.3.6.1.6.3.18.1.4.0', ''),
- ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
- ('1.3.6.1.2.1.1.1.0', 'my system')
+ ("1.3.6.1.2.1.1.3.0", 12345),
+ ("1.3.6.1.6.3.1.1.4.1.0", "1.3.6.1.6.3.1.1.5.2"),
+ ("1.3.6.1.6.3.18.1.3.0", "0.0.0.0"),
+ ("1.3.6.1.6.3.18.1.4.0", ""),
+ ("1.3.6.1.6.3.1.1.4.3.0", "1.3.6.1.4.1.20408.4.1.1.2"),
+ ("1.3.6.1.2.1.1.1.0", "my system"),
]
# Run var-binds through MIB resolver
# You may want to catch and ignore resolution errors here
-varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]
+varBinds = [
+ rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(
+ mibViewController
+ )
+ for x in varBinds
+]
for varBind in varBinds:
print(varBind.prettyPrint())
diff --git a/examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py b/examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py
index 1c794ca..8528e7c 100644
--- a/examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py
+++ b/examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py
@@ -9,7 +9,7 @@ or the other way around.
The code below does not explicitly add MIB compiler - that happens
behind the scenes. Examples below try to demo different kinds
of MIB objects to work with.
-"""#
+""" #
from pysnmp.smi import builder, view, rfc1902, error
# MIB Builder manages pysnmp MIBs
@@ -19,15 +19,15 @@ mibBuilder = builder.MibBuilder()
mibView = view.MibViewController(mibBuilder)
# Obtain MIB object information by MIB object name
-mibVar = rfc1902.ObjectIdentity('IF-MIB', 'ifInOctets', 1)
+mibVar = rfc1902.ObjectIdentity("IF-MIB", "ifInOctets", 1)
# Optionally attach PySMI MIB compiler to MIB Builder that would
# create pysnmp MIBs on demand from ASN.1 sources downloaded from
# a web site.
try:
- mibVar.addAsn1MibSource('https://pysnmp.github.io/mibs/asn1/@mib@')
+ mibVar.addAsn1MibSource("https://pysnmp.github.io/mibs/asn1/@mib@")
except error.SmiError:
- print('WARNING: not using MIB compiler (PySMI not installed)')
+ print("WARNING: not using MIB compiler (PySMI not installed)")
mibVar.resolveWithMib(mibView)
@@ -44,61 +44,70 @@ mibVar = rfc1902.ObjectIdentity(str(mibVar)).resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Obtain MIB object information by a mix of OID/label parts
-mibVar = rfc1902.ObjectIdentity((1, 3, 6, 1, 2, 'mib-2', 1, 'sysDescr')).resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity((1, 3, 6, 1, 2, "mib-2", 1, "sysDescr")).resolveWithMib(
+ mibView
+)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Obtain MIB object information by a label
-mibVar = rfc1902.ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr').resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity(
+ "iso.org.dod.internet.mgmt.mib-2.system.sysDescr"
+).resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Obtain the first MIB object in given MIB module
-mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB').resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity("SNMPv2-MIB").resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Obtain the last MIB object in given MIB module
-mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB', last=True).resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity("SNMPv2-MIB", last=True).resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Another way to obtain the first (or last) symbol in MIB module
-mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB', '').resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity("SNMPv2-MIB", "").resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Obtain MIB symbol from whatever MIB it is defined at (MIB should be loaded)
-mibVar = rfc1902.ObjectIdentity('', 'sysDescr', 0).resolveWithMib(mibView)
+mibVar = rfc1902.ObjectIdentity("", "sysDescr", 0).resolveWithMib(mibView)
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))
# Create an OID-value pair (called variable-binding in SNMP)
varBind = rfc1902.ObjectType(
- rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0), '1.3.6.1'
+ rfc1902.ObjectIdentity("SNMPv2-MIB", "sysObjectID", 0), "1.3.6.1"
).resolveWithMib(mibView)
print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint())
# Create just OID
varBind = rfc1902.ObjectType(
- rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0)
+ rfc1902.ObjectIdentity("SNMPv2-MIB", "sysObjectID", 0)
).resolveWithMib(mibView)
print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint())
# Create var-binds from MIB notification object (without OBJECTS clause)
varBinds = rfc1902.NotificationType(
- rfc1902.ObjectIdentity('SNMPv2-MIB', 'coldStart')
+ rfc1902.ObjectIdentity("SNMPv2-MIB", "coldStart")
).resolveWithMib(mibView)
-print([f'{x[0].prettyPrint()} = {x[1].__class__.__name__}({x[1].prettyPrint()})' for x in varBinds])
+print(
+ [
+ f"{x[0].prettyPrint()} = {x[1].__class__.__name__}({x[1].prettyPrint()})"
+ for x in varBinds
+ ]
+)
# Create var-binds from MIB notification object (with OBJECTS clause)
varBinds = rfc1902.NotificationType(
- rfc1902.ObjectIdentity('IF-MIB', 'linkUp'),
+ rfc1902.ObjectIdentity("IF-MIB", "linkUp"),
instanceIndex=(1,),
- objects={('IF-MIB', 'ifOperStatus'): 'down'}
+ objects={("IF-MIB", "ifOperStatus"): "down"},
).resolveWithMib(mibView)
print(varBinds.prettyPrint())
diff --git a/examples/smi/manager/mib-tree-inspection.py b/examples/smi/manager/mib-tree-inspection.py
index db1c955..6382096 100644
--- a/examples/smi/manager/mib-tree-inspection.py
+++ b/examples/smi/manager/mib-tree-inspection.py
@@ -6,78 +6,79 @@ This script explains how Python application (typically SNMP Manager)
could load SNMP MIB modules into memory and introspect Managed Objects
defined in MIB.
-"""#
+""" #
from pysnmp.smi import builder, view, compiler, error
# Create MIB loader/builder
mibBuilder = builder.MibBuilder()
# Optionally attach PySMI MIB compiler (if installed)
-#print('Attaching MIB compiler...'),
-#compiler.addMibCompiler(mibBuilder, sources=['/usr/share/snmp/mibs'])
-#print('done')
+# print('Attaching MIB compiler...'),
+# compiler.addMibCompiler(mibBuilder, sources=['/usr/share/snmp/mibs'])
+# print('done')
# Optionally set an alternative path to compiled MIBs
-print('Setting MIB sources...')
-mibBuilder.addMibSources(builder.DirMibSource('/opt/pysnmp_mibs'))
+print("Setting MIB sources...")
+mibBuilder.addMibSources(builder.DirMibSource("/opt/pysnmp_mibs"))
print(mibBuilder.getMibSources())
-print('done')
+print("done")
-print('Loading MIB modules...'),
+print("Loading MIB modules..."),
mibBuilder.loadModules(
- 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB', 'IP-MIB'
- )
-print('done')
+ "SNMPv2-MIB", "SNMP-FRAMEWORK-MIB", "SNMP-COMMUNITY-MIB", "IP-MIB"
+)
+print("done")
-print('Indexing MIB objects...'),
+print("Indexing MIB objects..."),
mibView = view.MibViewController(mibBuilder)
-print('done')
+print("done")
-print('MIB symbol name lookup by OID: '),
-oid, label, suffix = mibView.getNodeName((1,3,6,1,2,1,1,1))
+print("MIB symbol name lookup by OID: "),
+oid, label, suffix = mibView.getNodeName((1, 3, 6, 1, 2, 1, 1, 1))
print(oid, label, suffix)
-print('MIB symbol name lookup by label: '),
-oid, label, suffix = mibView.getNodeName((1,3,6,1,2,'mib-2',1,'sysDescr'))
+print("MIB symbol name lookup by label: "),
+oid, label, suffix = mibView.getNodeName((1, 3, 6, 1, 2, "mib-2", 1, "sysDescr"))
print(oid, label, suffix)
-print('MIB symbol name lookup by symbol description: '),
-oid, label, suffix = mibView.getNodeName(('sysDescr',))
-oid, label, suffix = mibView.getNodeName(('snmpEngineID',), 'SNMP-FRAMEWORK-MIB')
+print("MIB symbol name lookup by symbol description: "),
+oid, label, suffix = mibView.getNodeName(("sysDescr",))
+oid, label, suffix = mibView.getNodeName(("snmpEngineID",), "SNMP-FRAMEWORK-MIB")
print(oid, label, suffix)
-print('MIB object value pretty print: '),
-mibNode, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'snmpEngineID')
+print("MIB object value pretty print: "),
+(mibNode,) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpEngineID")
print(mibNode.syntax.prettyPrint())
-print('MIB symbol location lookup by name: '),
-modName, symName, suffix = mibView.getNodeLocation(('snmpCommunityEntry',))
+print("MIB symbol location lookup by name: "),
+modName, symName, suffix = mibView.getNodeLocation(("snmpCommunityEntry",))
print(symName, modName)
-print('MIB node lookup by location: '),
-rowNode, = mibBuilder.importSymbols(modName, symName)
+print("MIB node lookup by location: "),
+(rowNode,) = mibBuilder.importSymbols(modName, symName)
print(rowNode)
-print('Conceptual table index value to oid conversion: '),
-oid = rowNode.getInstIdFromIndices('router')
+print("Conceptual table index value to oid conversion: "),
+oid = rowNode.getInstIdFromIndices("router")
print(oid)
-print('Conceptual table index oid to value conversion: '),
+print("Conceptual table index oid to value conversion: "),
print(rowNode.getIndicesFromInstId(oid))
-print('MIB tree traversal')
+print("MIB tree traversal")
oid, label, suffix = mibView.getFirstNodeName()
while 1:
try:
modName, nodeDesc, suffix = mibView.getNodeLocation(oid)
- print(f'{modName}::{nodeDesc} == {oid}')
+ print(f"{modName}::{nodeDesc} == {oid}")
oid, label, suffix = mibView.getNextNodeName(oid)
except error.NoSuchObjectError:
break
-print('Modules traversal')
+print("Modules traversal")
modName = mibView.getFirstModuleName()
while 1:
- if modName: print(modName)
+ if modName:
+ print(modName)
try:
modName = mibView.getNextModuleName(modName)
except error.SmiError:
diff --git a/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py
index 25a396c..2a697b5 100644
--- a/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py
+++ b/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py
@@ -18,7 +18,7 @@ Either of the following Net-SNMP commands will walk this Agent:
The Command Receiver below uses two distinct transports for communication
with Command Generators - UDP over IPv4 and UDP over IPv6.
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp, udp6, unix
from pyasn1.codec.ber import encoder, decoder
@@ -29,21 +29,27 @@ import time, bisect
class SysDescr:
name = (1, 3, 6, 1, 2, 1, 1, 1, 0)
- def __eq__(self, other): return self.name == other
+ def __eq__(self, other):
+ return self.name == other
- def __ne__(self, other): return self.name != other
+ def __ne__(self, other):
+ return self.name != other
- def __lt__(self, other): return self.name < other
+ def __lt__(self, other):
+ return self.name < other
- def __le__(self, other): return self.name <= other
+ def __le__(self, other):
+ return self.name <= other
- def __gt__(self, other): return self.name > other
+ def __gt__(self, other):
+ return self.name > other
- def __ge__(self, other): return self.name >= other
+ def __ge__(self, other):
+ return self.name >= other
def __call__(self, protoVer):
return api.protoModules[protoVer].OctetString(
- 'PySNMP example command responder'
+ "PySNMP example command responder"
)
@@ -51,27 +57,29 @@ class Uptime:
name = (1, 3, 6, 1, 2, 1, 1, 3, 0)
birthday = time.time()
- def __eq__(self, other): return self.name == other
+ def __eq__(self, other):
+ return self.name == other
- def __ne__(self, other): return self.name != other
+ def __ne__(self, other):
+ return self.name != other
- def __lt__(self, other): return self.name < other
+ def __lt__(self, other):
+ return self.name < other
- def __le__(self, other): return self.name <= other
+ def __le__(self, other):
+ return self.name <= other
- def __gt__(self, other): return self.name > other
+ def __gt__(self, other):
+ return self.name > other
- def __ge__(self, other): return self.name >= other
+ def __ge__(self, other):
+ return self.name >= other
def __call__(self, protoVer):
- return api.protoModules[protoVer].TimeTicks(
- (time.time() - self.birthday) * 100
- )
+ return api.protoModules[protoVer].TimeTicks((time.time() - self.birthday) * 100)
-mibInstr = (
- SysDescr(), Uptime() # sorted by object name
-)
+mibInstr = (SysDescr(), Uptime()) # sorted by object name
mibInstrIdx = {}
for mibVar in mibInstr:
@@ -84,10 +92,11 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
- print('Unsupported SNMP version %s' % msgVer)
+ print("Unsupported SNMP version %s" % msgVer)
return
reqMsg, wholeMsg = decoder.decode(
- wholeMsg, asn1Spec=pMod.Message(),
+ wholeMsg,
+ asn1Spec=pMod.Message(),
)
rspMsg = pMod.apiMessage.getResponse(reqMsg)
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -105,14 +114,10 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
if nextIdx == len(mibInstr):
# Out of MIB
varBinds.append((oid, val))
- pendingErrors.append(
- (pMod.apiPDU.setEndOfMibError, errorIndex)
- )
+ pendingErrors.append((pMod.apiPDU.setEndOfMibError, errorIndex))
else:
# Report value if OID is found
- varBinds.append(
- (mibInstr[nextIdx].name, mibInstr[nextIdx](msgVer))
- )
+ varBinds.append((mibInstr[nextIdx].name, mibInstr[nextIdx](msgVer)))
elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
if oid in mibInstrIdx:
@@ -126,7 +131,7 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
break
else:
# Report unsupported request type
- pMod.apiPDU.setErrorStatus(rspPDU, 'genErr')
+ pMod.apiPDU.setErrorStatus(rspPDU, "genErr")
pMod.apiPDU.setVarBinds(rspPDU, varBinds)
# Commit possible error indices to response PDU
for f, i in pendingErrors:
@@ -142,12 +147,12 @@ transportDispatcher.registerRecvCbFun(cbFun)
# UDP/IPv4
transportDispatcher.registerTransport(
- udp.domainName, udp.UdpSocketTransport().openServerMode(('localhost', 161))
+ udp.domainName, udp.UdpSocketTransport().openServerMode(("localhost", 161))
)
# UDP/IPv6
transportDispatcher.registerTransport(
- udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 161))
+ udp6.domainName, udp6.Udp6SocketTransport().openServerMode(("::1", 161))
)
## Local domain socket
diff --git a/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py
index 50a3256..ac08db7 100644
--- a/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py
+++ b/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py
@@ -8,15 +8,15 @@ The following script sends SNMP INFORM notification using the following options:
* with community name 'public'
* over IPv4/UDP and IPv6/UDP
* send INFORM notification
-* to a Manager at demo.snmplabs.com:162 and [::1]:162
+* to a Manager at localhost:162 and [::1]:162
* with TRAP ID 'coldStart' specified as an OID
The following Net-SNMP command will produce similar SNMP notification:
-| $ snmpinform -v2c -c public udp:demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1
+| $ snmpinform -v2c -c public udp:localhost 0 1.3.6.1.6.3.1.1.5.1
| $ snmpinform -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from time import time
from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher
from pysnmp.carrier.asynsock.dgram import udp, udp6
@@ -30,7 +30,7 @@ pMod.apiTrapPDU.setDefaults(reqPDU)
# Build message
trapMsg = pMod.Message()
pMod.apiMessage.setDefaults(trapMsg)
-pMod.apiMessage.setCommunity(trapMsg, 'public')
+pMod.apiMessage.setCommunity(trapMsg, "public")
pMod.apiMessage.setPDU(trapMsg, reqPDU)
startedAt = time()
@@ -42,8 +42,9 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU):
+def cbRecvFun(
+ transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -54,9 +55,9 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
if errorStatus:
print(errorStatus.prettyPrint())
else:
- print('INFORM message delivered, response var-binds follow')
+ print("INFORM message delivered, response var-binds follow")
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
transportDispatcher.jobFinished(1)
return wholeMsg
@@ -71,7 +72,7 @@ transportDispatcher.registerTransport(
udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
- encoder.encode(trapMsg), udp.domainName, ('demo.snmplabs.com', 162)
+ encoder.encode(trapMsg), udp.domainName, ("localhost", 162)
)
transportDispatcher.jobStarted(1)
diff --git a/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py
index 695adc2..4c5ab7f 100644
--- a/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py
+++ b/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py
@@ -9,7 +9,7 @@ following options:
* with community name 'public'
* over IPv4/UDP and IPv6/UDP
* send TRAP notification
-* to a Manager at demo.snmplabs.com:162 and [::1]
+* to a Manager at localhost:162 and [::1]
* with TRAP ID 'coldStart' specified as an OID
* include managed objects information:
* with default Uptime value
@@ -18,10 +18,10 @@ following options:
The following Net-SNMP commands will produce similar SNMP notification:
-| $ snmptrap -v1 -c public udp:demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345
+| $ snmptrap -v1 -c public udp:localhost 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345
| $ snmptrap -v1 -c public udp6:[::1] 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp, udp6, unix
from pyasn1.codec.ber import encoder
@@ -38,12 +38,12 @@ pMod.apiTrapPDU.setDefaults(trapPDU)
# Traps have quite different semantics across proto versions
if pMod == api.protoModules[api.protoVersion1]:
pMod.apiTrapPDU.setEnterprise(trapPDU, (1, 3, 6, 1, 1, 2, 3, 4, 1))
- pMod.apiTrapPDU.setGenericTrap(trapPDU, 'coldStart')
+ pMod.apiTrapPDU.setGenericTrap(trapPDU, "coldStart")
# Build message
trapMsg = pMod.Message()
pMod.apiMessage.setDefaults(trapMsg)
-pMod.apiMessage.setCommunity(trapMsg, 'public')
+pMod.apiMessage.setCommunity(trapMsg, "public")
pMod.apiMessage.setPDU(trapMsg, trapPDU)
transportDispatcher = AsyncoreDispatcher()
@@ -53,16 +53,14 @@ transportDispatcher.registerTransport(
udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
- encoder.encode(trapMsg), udp.domainName, ('demo.snmplabs.com', 162)
+ encoder.encode(trapMsg), udp.domainName, ("localhost", 162)
)
# UDP/IPv6
transportDispatcher.registerTransport(
udp6.domainName, udp6.Udp6SocketTransport().openClientMode()
)
-transportDispatcher.sendMessage(
- encoder.encode(trapMsg), udp6.domainName, ('::1', 162)
-)
+transportDispatcher.sendMessage(encoder.encode(trapMsg), udp6.domainName, ("::1", 162))
## Local domain socket
# transportDispatcher.registerTransport(
diff --git a/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py b/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py
index c2d7dee..3c82347 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py
@@ -19,7 +19,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v2c -c public -ObentU 255.255.255.255 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
@@ -38,20 +38,20 @@ pMod = api.protoModules[api.protoVersion2c]
reqPDU = pMod.GetRequestPDU()
pMod.apiPDU.setDefaults(reqPDU)
pMod.apiPDU.setVarBinds(
- reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')),
- ('1.3.6.1.2.1.1.3.0', pMod.Null('')))
+ reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null("")))
)
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
-pMod.apiMessage.setCommunity(reqMsg, 'public')
+pMod.apiMessage.setCommunity(reqMsg, "public")
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
-class StopWaiting(Exception): pass
+class StopWaiting(Exception):
+ pass
def cbTimerFun(timeNow):
@@ -60,8 +60,9 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU):
+def cbRecvFun(
+ transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -73,7 +74,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
transportDispatcher.jobFinished(1)
return wholeMsg
@@ -89,7 +90,7 @@ transportDispatcher.registerTransport(udp.domainName, udpSocketTransport)
# Pass message to dispatcher
transportDispatcher.sendMessage(
- encoder.encode(reqMsg), udp.domainName, ('255.255.255.255', 161)
+ encoder.encode(reqMsg), udp.domainName, ("255.255.255.255", 161)
)
# wait for a maximum of 10 responses or time out
diff --git a/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py b/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py
index d33a23b..e386a8c 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py
@@ -6,14 +6,14 @@ Perform SNMP GET operation with the following options:
* with SNMPv1, community 'public'
* over IPv4/UDP
-* to an Agent at demo.snmplabs.com:161
+* to an Agent at localhost:161
* for OIDs in tuple form
This script performs similar to the following Net-SNMP command:
-| $ snmpget -v1 -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0
+| $ snmpget -v1 -c public -ObentU localhost 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp, udp6, unix
from pyasn1.codec.ber import encoder, decoder
@@ -28,14 +28,13 @@ pMod = api.protoModules[api.protoVersion1]
reqPDU = pMod.GetRequestPDU()
pMod.apiPDU.setDefaults(reqPDU)
pMod.apiPDU.setVarBinds(
- reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')),
- ('1.3.6.1.2.1.1.3.0', pMod.Null('')))
+ reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null("")))
)
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
-pMod.apiMessage.setCommunity(reqMsg, 'public')
+pMod.apiMessage.setCommunity(reqMsg, "public")
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
@@ -47,8 +46,9 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU):
+def cbRecvFun(
+ transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -60,7 +60,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
transportDispatcher.jobFinished(1)
return wholeMsg
@@ -77,7 +77,7 @@ transportDispatcher.registerTransport(
# Pass message to dispatcher
transportDispatcher.sendMessage(
- encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161)
+ encoder.encode(reqMsg), udp.domainName, ("localhost", 161)
)
transportDispatcher.jobStarted(1)
diff --git a/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py b/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py
index 625e34c..7a84b39 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py
@@ -6,15 +6,15 @@ Perform SNMP GETBULK operation with the following options:
* with SNMPv2c, community 'public'
* over IPv4/UDP
-* to an Agent at demo.snmplabs.com:161
+* to an Agent at localhost:161
* for OID in tuple form
* with non-repeaters=0 and max-repeaters=25
This script performs similar to the following Net-SNMP command:
-| $ snmpbulkwalk -v2c -c public -ObentU -Cn0 -Cr25 demo.snmplabs.com 1.3.6
+| $ snmpbulkwalk -v2c -c public -ObentU -Cn0 -Cr25 localhost 1.3.6
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
@@ -34,7 +34,7 @@ v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars])
# Build message
reqMsg = v2c.Message()
v2c.apiMessage.setDefaults(reqMsg)
-v2c.apiMessage.setCommunity(reqMsg, 'public')
+v2c.apiMessage.setCommunity(reqMsg, "public")
v2c.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
@@ -46,8 +46,14 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU, headVars=headVars):
+def cbRecvFun(
+ transportDispatcher,
+ transportDomain,
+ transportAddress,
+ wholeMsg,
+ reqPDU=reqPDU,
+ headVars=headVars,
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message())
@@ -62,18 +68,23 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU)
if errorStatus and errorStatus != 2:
errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU)
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[int(errorIndex) - 1] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[int(errorIndex) - 1] or "?",
+ )
+ )
transportDispatcher.jobFinished(1)
break
# Report SNMP table
for tableRow in varBindTable:
for name, val in tableRow:
- print('from: {}, {} = {}'.format(
- transportAddress, name.prettyPrint(), val.prettyPrint()
+ print(
+ "from: {}, {} = {}".format(
+ transportAddress, name.prettyPrint(), val.prettyPrint()
+ )
)
- )
# Stop on EOM
for oid, val in varBindTable[-1]:
@@ -92,7 +103,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
)
global startedAt
if time() - startedAt > 3:
- raise Exception('Request timed out')
+ raise Exception("Request timed out")
startedAt = time()
return wholeMsg
@@ -106,7 +117,7 @@ transportDispatcher.registerTransport(
udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
- encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161)
+ encoder.encode(reqMsg), udp.domainName, ("localhost", 161)
)
transportDispatcher.jobStarted(1)
diff --git a/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py b/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py
index 167c6b3..e2fe4e6 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py
@@ -6,14 +6,14 @@ Perform SNMP GETNEXT operation with the following options:
* with SNMPv1, community 'public'
* over IPv4/UDP
-* to an Agent at demo.snmplabs.com:161
+* to an Agent at localhost:161
* for OID in tuple form
This script performs similar to the following Net-SNMP command:
-| $ snmpwalk -v1 -c public -ObentU demo.snmplabs.com 1.3.6
+| $ snmpwalk -v1 -c public -ObentU localhost 1.3.6
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
@@ -35,7 +35,7 @@ pMod.apiPDU.setVarBinds(reqPDU, [(x, pMod.null) for x in headVars])
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
-pMod.apiMessage.setCommunity(reqMsg, 'public')
+pMod.apiMessage.setCommunity(reqMsg, "public")
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
@@ -47,8 +47,14 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU, headVars=headVars):
+def cbRecvFun(
+ transportDispatcher,
+ transportDomain,
+ transportAddress,
+ wholeMsg,
+ reqPDU=reqPDU,
+ headVars=headVars,
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -63,10 +69,11 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
# Report SNMP table
for tableRow in varBindTable:
for name, val in tableRow:
- print('from: {}, {} = {}'.format(
- transportAddress, name.prettyPrint(), val.prettyPrint()
+ print(
+ "from: {}, {} = {}".format(
+ transportAddress, name.prettyPrint(), val.prettyPrint()
+ )
)
- )
# Stop on EOM
for oid, val in varBindTable[-1]:
if not isinstance(val, pMod.Null):
@@ -84,7 +91,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
)
global startedAt
if time() - startedAt > 3:
- raise Exception('Request timed out')
+ raise Exception("Request timed out")
startedAt = time()
return wholeMsg
@@ -98,7 +105,7 @@ transportDispatcher.registerTransport(
udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
- encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161)
+ encoder.encode(reqMsg), udp.domainName, ("localhost", 161)
)
transportDispatcher.jobStarted(1)
diff --git a/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py b/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py
index f03ed2a..0dafa2e 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py
@@ -27,7 +27,7 @@ Agent would respond to the IP address you used as a source. So this script
could only get a response if that source address is somehow routed to the
host this script is running on. Otherwise it just times out.
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.proto import api
@@ -35,10 +35,10 @@ from pyasn1.codec.ber import encoder, decoder
from time import time
# Send request message to this address
-transportAddress = udp.UdpTransportAddress(('104.236.166.95', 161))
+transportAddress = udp.UdpTransportAddress(("104.236.166.95", 161))
# Send request message from this non-local (!) IP address
-transportAddress.setLocalAddress(('1.2.3.4', 0))
+transportAddress.setLocalAddress(("1.2.3.4", 0))
# Protocol version to use
# pMod = api.protoModules[api.protoVersion1]
@@ -48,20 +48,20 @@ pMod = api.protoModules[api.protoVersion2c]
reqPDU = pMod.GetRequestPDU()
pMod.apiPDU.setDefaults(reqPDU)
pMod.apiPDU.setVarBinds(
- reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')),
- ('1.3.6.1.2.1.1.3.0', pMod.Null('')))
+ reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null("")))
)
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
-pMod.apiMessage.setCommunity(reqMsg, 'public')
+pMod.apiMessage.setCommunity(reqMsg, "public")
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
-class StopWaiting(Exception): pass
+class StopWaiting(Exception):
+ pass
def cbTimerFun(timeNow):
@@ -70,8 +70,9 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU):
+def cbRecvFun(
+ transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -83,7 +84,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
transportDispatcher.jobFinished(1)
return wholeMsg
diff --git a/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py b/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py
index f90f9f9..05a6fa5 100644
--- a/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py
+++ b/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py
@@ -6,14 +6,14 @@ Perform SNMP SET operation with the following options:
* with SNMPv2c, community 'public'
* over IPv4/UDP
-* to an Agent at demo.snmplabs.com:161
+* to an Agent at localhost:161
* for OIDs in string form and values in form of pyasn1 objects
This script performs similar to the following Net-SNMP command:
-| $ snmpset -v2c -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1.1.9.1.3.1 s 'New description' 1.3.6.1.2.1.1.9.1.4.1 t 12
+| $ snmpset -v2c -c public -ObentU localhost 1.3.6.1.2.1.1.9.1.3.1 s 'New description' 1.3.6.1.2.1.1.9.1.4.1 t 12
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
@@ -30,14 +30,16 @@ pMod.apiPDU.setDefaults(reqPDU)
pMod.apiPDU.setVarBinds(
reqPDU,
# A list of Var-Binds to SET
- (('1.3.6.1.2.1.1.9.1.3.1', pMod.OctetString('New system description')),
- ('1.3.6.1.2.1.1.9.1.4.1', pMod.TimeTicks(12)))
+ (
+ ("1.3.6.1.2.1.1.9.1.3.1", pMod.OctetString("New system description")),
+ ("1.3.6.1.2.1.1.9.1.4.1", pMod.TimeTicks(12)),
+ ),
)
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
-pMod.apiMessage.setCommunity(reqMsg, 'public')
+pMod.apiMessage.setCommunity(reqMsg, "public")
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
@@ -49,8 +51,9 @@ def cbTimerFun(timeNow):
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
- wholeMsg, reqPDU=reqPDU):
+def cbRecvFun(
+ transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU
+):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
@@ -62,7 +65,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
transportDispatcher.jobFinished(1)
return wholeMsg
@@ -79,7 +82,7 @@ transportDispatcher.registerTransport(
# Pass message to dispatcher
transportDispatcher.sendMessage(
- encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161)
+ encoder.encode(reqMsg), udp.domainName, ("localhost", 161)
)
transportDispatcher.jobStarted(1)
diff --git a/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py
index 877c863..11ef3a0 100644
--- a/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py
+++ b/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py
@@ -19,7 +19,7 @@ receiver:
Notification Receiver below uses two different transports for communication
with Notification Originators - UDP over IPv4 and UDP over IPv6.
-"""#
+""" #
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp, udp6, unix
from pyasn1.codec.ber import decoder
@@ -33,29 +33,45 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
- print('Unsupported SNMP version %s' % msgVer)
+ print("Unsupported SNMP version %s" % msgVer)
return
reqMsg, wholeMsg = decoder.decode(
- wholeMsg, asn1Spec=pMod.Message(),
+ wholeMsg,
+ asn1Spec=pMod.Message(),
)
- print('Notification message from {}:{}: '.format(
- transportDomain, transportAddress
+ print(
+ "Notification message from {}:{}: ".format(
+ transportDomain, transportAddress
+ )
)
- )
reqPDU = pMod.apiMessage.getPDU(reqMsg)
if reqPDU.isSameTypeWith(pMod.TrapPDU()):
if msgVer == api.protoVersion1:
- print('Enterprise: %s' % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()))
- print('Agent Address: %s' % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()))
- print('Generic Trap: %s' % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()))
- print('Specific Trap: %s' % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()))
- print('Uptime: %s' % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()))
+ print(
+ "Enterprise: %s"
+ % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())
+ )
+ print(
+ "Agent Address: %s"
+ % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
+ )
+ print(
+ "Generic Trap: %s"
+ % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())
+ )
+ print(
+ "Specific Trap: %s"
+ % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())
+ )
+ print(
+ "Uptime: %s" % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())
+ )
varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU)
else:
varBinds = pMod.apiPDU.getVarBinds(reqPDU)
- print('Var-binds:')
+ print("Var-binds:")
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return wholeMsg
@@ -65,12 +81,12 @@ transportDispatcher.registerRecvCbFun(cbFun)
# UDP/IPv4
transportDispatcher.registerTransport(
- udp.domainName, udp.UdpSocketTransport().openServerMode(('localhost', 162))
+ udp.domainName, udp.UdpSocketTransport().openServerMode(("localhost", 162))
)
# UDP/IPv6
transportDispatcher.registerTransport(
- udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 162))
+ udp6.domainName, udp6.Udp6SocketTransport().openServerMode(("::1", 162))
)
## Local domain socket
diff --git a/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py b/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py
index e3ee3aa..0fb42bc 100644
--- a/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py
+++ b/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py
@@ -22,7 +22,7 @@ Either of the following Net-SNMP commands will walk this Agent:
Requires Python 3.4 and later!
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncio.dgram import udp
@@ -39,35 +39,42 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# user: usr-sha-none, auth: SHA, priv NONE
-config.addV3User(
- snmpEngine, 'usr-sha-none',
- config.usmHMACSHAAuthProtocol, 'authkey1'
-)
+config.addV3User(snmpEngine, "usr-sha-none", config.usmHMACSHAAuthProtocol, "authkey1")
# user: usr-sha-none, auth: SHA, priv AES
config.addV3User(
- snmpEngine, 'usr-sha-aes128',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1'
+ snmpEngine,
+ "usr-sha-aes128",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
)
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
-config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
-config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
+config.addVacmUser(
+ snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
+config.addVacmUser(
+ snmpEngine, 3, "usr-sha-aes128", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py b/examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py
index 81778b4..ba17f0b 100644
--- a/examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py
+++ b/examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py
@@ -19,7 +19,7 @@ receiver:
Requires Python 3.4 and later!
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncio.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
@@ -38,35 +38,35 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 162)),
)
# UDP over IPv4, second listening interface/port
config.addTransport(
snmpEngine,
udp.domainName + (2,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 2162))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 2162)),
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal
-def cbFun(snmpEngine,
- stateReference,
- contextEngineId, contextName,
- varBinds,
- cbCtx):
- transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)
- print('Notification from {}, SNMP Engine {}, Context {}'.format(transportAddress,
- contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(
+ stateReference
+ )
+ print(
+ "Notification from {}, SNMP Engine {}, Context {}".format(
+ transportAddress, contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py b/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py
index 5903b54..ed9e370 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py
@@ -17,7 +17,7 @@ Either of the following Net-SNMP commands will walk this Agent:
| $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 -n my-context 127.0.0.1 .1.3.6
| $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 127.0.0.1 .1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -31,33 +31,30 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv3/USM setup
# user: usr-md5-none, auth: MD5, priv NONE
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Create an SNMP context with ContextEngineId = 8000000001020304
snmpContext = context.SnmpContext(
- snmpEngine, contextEngineId=v2c.OctetString(hexValue='8000000001020304')
+ snmpEngine, contextEngineId=v2c.OctetString(hexValue="8000000001020304")
)
# Create an [empty] set of Managed Objects (MibBuilder), pass it to
# Management Instrumentation Controller and register at SNMP Context
# under ContextName 'my-context'
snmpContext.registerContextName(
- v2c.OctetString('my-context'), # Context Name
- instrum.MibInstrumController(builder.MibBuilder()) # Managed Objects
+ v2c.OctetString("my-context"), # Context Name
+ instrum.MibInstrumController(builder.MibBuilder()), # Managed Objects
)
# Register SNMP Applications at the SNMP engine for particular SNMP context
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py b/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py
index 1a03e72..9075530 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py
@@ -16,7 +16,7 @@ The following Net-SNMP command will send GET request to this Agent:
| $ snmpget -v3 -u usr-none-none -l noAuthNoPriv -n my-context -Ir 127.0.0.1 sysDescr.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -30,20 +30,23 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv3/USM setup
# user: usr-none-none, auth: NONE, priv NONE
-config.addV3User(
- snmpEngine, 'usr-none-none'
-)
+config.addV3User(snmpEngine, "usr-none-none")
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine,
+ 3,
+ "usr-none-none",
+ "noAuthNoPriv",
+ (1, 3, 6, 1, 2, 1),
+ (1, 3, 6, 1, 2, 1),
+)
# Create an SNMP context
snmpContext = context.SnmpContext(snmpEngine)
@@ -54,14 +57,16 @@ snmpContext = context.SnmpContext(snmpEngine)
# always echos request var-binds in response.
class EchoMibInstrumController(instrum.AbstractMibInstrumController):
def readVars(self, varBinds, acInfo=(None, None)):
- return [(ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in varBinds]
+ return [
+ (ov[0], v2c.OctetString("You queried OID %s" % ov[0])) for ov in varBinds
+ ]
# Create a custom Management Instrumentation Controller and register at
# SNMP Context under ContextName 'my-context'
snmpContext.registerContextName(
- v2c.OctetString('my-context'), # Context Name
- EchoMibInstrumController() # Management Instrumentation
+ v2c.OctetString("my-context"), # Context Name
+ EchoMibInstrumController(), # Management Instrumentation
)
# Register GET&SET Applications at the SNMP engine for a custom SNMP context
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py b/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py
index 5e9a535..fc2989c 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py
@@ -15,35 +15,38 @@ The following Net-SNMP command will walk this Agent:
| $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000004030201 localhost .1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.proto import rfc1902
# Create SNMP engine
-snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue='8000000004030201'))
+snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue="8000000004030201"))
# Transport setup
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py b/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py
index 7f82dde..bc217e4 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py
@@ -29,7 +29,7 @@ However this command will fail:
This command will not reveal `SNMPv2-MIB::sysUpTime.0` among other objects:
| $ snmpwalk -v2c -c public 127.0.0.1 SNMPv2-MIB::system
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -42,38 +42,40 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# Register default MIB instrumentation controller with a new SNMP context
-contextName = 'abcd'
+contextName = "abcd"
snmpContext = context.SnmpContext(snmpEngine)
snmpContext.registerContextName(
- contextName, snmpEngine.msgAndPduDsp.mibInstrumController)
+ contextName, snmpEngine.msgAndPduDsp.mibInstrumController
+)
# Add new SNMP community name, map it to a new security name and
# SNMP context
-securityName = 'my-area'
-communityName = 'public'
+securityName = "my-area"
+communityName = "public"
config.addV1System(
- snmpEngine, securityName, communityName,
+ snmpEngine,
+ securityName,
+ communityName,
contextEngineId=snmpContext.contextEngineId,
- contextName=contextName)
+ contextName=contextName,
+)
# VACM configuration settings
securityModel = 2 # SNMPv2c
securityLevel = 1 # noAuthNoPriv
-vacmGroup = 'my-group'
-readViewName = 'my-read-view'
+vacmGroup = "my-group"
+readViewName = "my-read-view"
# We will match by context name prefix
contextPrefix = contextName[:1]
@@ -82,23 +84,32 @@ contextPrefix = contextName[:1]
config.addContext(snmpEngine, contextName)
# Populate SNMP-VIEW-BASED-ACM-MIB::vacmSecurityToGroupTable
-config.addVacmGroup(
- snmpEngine, vacmGroup, securityModel, securityName)
+config.addVacmGroup(snmpEngine, vacmGroup, securityModel, securityName)
# Populate SNMP-VIEW-BASED-ACM-MIB::vacmAccessTable
config.addVacmAccess(
- snmpEngine, vacmGroup, contextPrefix, securityModel, securityLevel,
- 'prefix', readViewName, '', '')
+ snmpEngine,
+ vacmGroup,
+ contextPrefix,
+ securityModel,
+ securityLevel,
+ "prefix",
+ readViewName,
+ "",
+ "",
+)
# Populate SNMP-VIEW-BASED-ACM-MIB::vacmViewTreeFamilyTable
# Allow the whole system subtree
config.addVacmView(
- snmpEngine, readViewName, 'included', '1.3.6.1.2.1.1.1', '1.1.1.1.1.1.1.0')
+ snmpEngine, readViewName, "included", "1.3.6.1.2.1.1.1", "1.1.1.1.1.1.1.0"
+)
# ...but exclude one sub-branch (just one scalar OID)
config.addVacmView(
- snmpEngine, readViewName, 'excluded', '1.3.6.1.2.1.1.3', '1.1.1.1.1.1.1.1')
+ snmpEngine, readViewName, "excluded", "1.3.6.1.2.1.1.3", "1.1.1.1.1.1.1.1"
+)
# Register SNMP Applications at the SNMP engine for particular SNMP context
cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py b/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py
index 0fa099d..34a7e7d 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py
@@ -15,7 +15,7 @@ The following Net-SNMP commands will walk this Agent:
| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6
-"""#
+""" #
import sys
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
@@ -29,18 +29,16 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv2c setup
# SecurityName <-> CommunityName mapping.
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Allow read MIB access for this user / securityModels at VACM
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 5))
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 5))
# Create an SNMP context
snmpContext = context.SnmpContext(snmpEngine)
@@ -50,7 +48,7 @@ snmpContext = context.SnmpContext(snmpEngine)
mibBuilder = snmpContext.getMibInstrum().getMibBuilder()
MibScalar, MibScalarInstance = mibBuilder.importSymbols(
- 'SNMPv2-SMI', 'MibScalar', 'MibScalarInstance'
+ "SNMPv2-SMI", "MibScalar", "MibScalarInstance"
)
@@ -58,13 +56,14 @@ class MyStaticMibScalarInstance(MibScalarInstance):
# noinspection PyUnusedLocal,PyUnusedLocal
def getValue(self, name, idx):
return self.getSyntax().clone(
- f'Python {sys.version} running on a {sys.platform} platform'
+ f"Python {sys.version} running on a {sys.platform} platform"
)
mibBuilder.exportSymbols(
- '__MY_MIB', MibScalar((1, 3, 6, 5, 1), v2c.OctetString()),
- MyStaticMibScalarInstance((1, 3, 6, 5, 1), (0,), v2c.OctetString())
+ "__MY_MIB",
+ MibScalar((1, 3, 6, 5, 1), v2c.OctetString()),
+ MyStaticMibScalarInstance((1, 3, 6, 5, 1), (0,), v2c.OctetString()),
)
# --- end of Managed Object Instance initialization ----
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py b/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py
index 0e15599..2317c1d 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py
@@ -23,7 +23,7 @@ The following Net-SNMP commands will populate and walk a table:
| $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 6
| $ snmpwalk -v2c -c public 127.0.0.1 1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -36,18 +36,16 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv2c setup
# SecurityName <-> CommunityName mapping.
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Allow read MIB access for this user / securityModels at VACM
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 6), (1, 3, 6, 6))
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 6), (1, 3, 6, 6))
# Create an SNMP context
snmpContext = context.SnmpContext(snmpEngine)
@@ -56,55 +54,62 @@ snmpContext = context.SnmpContext(snmpEngine)
mibBuilder = snmpContext.getMibInstrum().getMibBuilder()
-(MibTable,
- MibTableRow,
- MibTableColumn,
- MibScalarInstance) = mibBuilder.importSymbols(
- 'SNMPv2-SMI',
- 'MibTable',
- 'MibTableRow',
- 'MibTableColumn',
- 'MibScalarInstance'
+(MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols(
+ "SNMPv2-SMI", "MibTable", "MibTableRow", "MibTableColumn", "MibScalarInstance"
)
-RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus')
+(RowStatus,) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus")
mibBuilder.exportSymbols(
- '__EXAMPLE-MIB',
+ "__EXAMPLE-MIB",
# table object
- exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess('readcreate'),
+ exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess("readcreate"),
# table row object, also carries references to table indices
- exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)).setMaxAccess('readcreate').setIndexNames((0, '__EXAMPLE-MIB', 'exampleTableColumn1')),
+ exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5))
+ .setMaxAccess("readcreate")
+ .setIndexNames((0, "__EXAMPLE-MIB", "exampleTableColumn1")),
# table column: string index
- exampleTableColumn1=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.OctetString()).setMaxAccess('readcreate'),
+ exampleTableColumn1=MibTableColumn(
+ (1, 3, 6, 6, 1, 5, 1), v2c.OctetString()
+ ).setMaxAccess("readcreate"),
# table column: string value
- exampleTableColumn2=MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()).setMaxAccess('readcreate'),
+ exampleTableColumn2=MibTableColumn(
+ (1, 3, 6, 6, 1, 5, 2), v2c.OctetString()
+ ).setMaxAccess("readcreate"),
# table column: integer value with default
- exampleTableColumn3=MibTableColumn((1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)).setMaxAccess('readcreate'),
+ exampleTableColumn3=MibTableColumn(
+ (1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)
+ ).setMaxAccess("readcreate"),
# table column: row status
- exampleTableStatus=MibTableColumn((1, 3, 6, 6, 1, 5, 4), RowStatus('notExists')).setMaxAccess('readcreate')
+ exampleTableStatus=MibTableColumn(
+ (1, 3, 6, 6, 1, 5, 4), RowStatus("notExists")
+ ).setMaxAccess("readcreate"),
)
# --- end of custom SNMP table definition, empty table now exists ---
# --- populate custom SNMP table with one row ---
-(exampleTableEntry,
- exampleTableColumn2,
- exampleTableColumn3,
- exampleTableStatus) = mibBuilder.importSymbols(
- '__EXAMPLE-MIB',
- 'exampleTableEntry',
- 'exampleTableColumn2',
- 'exampleTableColumn3',
- 'exampleTableStatus'
+(
+ exampleTableEntry,
+ exampleTableColumn2,
+ exampleTableColumn3,
+ exampleTableStatus,
+) = mibBuilder.importSymbols(
+ "__EXAMPLE-MIB",
+ "exampleTableEntry",
+ "exampleTableColumn2",
+ "exampleTableColumn3",
+ "exampleTableStatus",
)
-rowInstanceId = exampleTableEntry.getInstIdFromIndices('example record one')
+rowInstanceId = exampleTableEntry.getInstIdFromIndices("example record one")
mibInstrumentation = snmpContext.getMibInstrum()
mibInstrumentation.writeVars(
- ((exampleTableColumn2.name + rowInstanceId, 'my string value'),
- (exampleTableColumn3.name + rowInstanceId, 123456),
- (exampleTableStatus.name + rowInstanceId, 'createAndGo'))
+ (
+ (exampleTableColumn2.name + rowInstanceId, "my string value"),
+ (exampleTableColumn3.name + rowInstanceId, 123456),
+ (exampleTableStatus.name + rowInstanceId, "createAndGo"),
+ )
)
# --- end of SNMP table population ---
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py
index ef5c623..f65921a 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py
@@ -16,7 +16,7 @@ Either of the following Net-SNMP commands will walk this Agent:
| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6
| $ snmpwalk -v2c -c public udp6:[::1] .1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp, udp6
@@ -29,24 +29,22 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4 at 127.0.0.1:161
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# UDP over IPv6 at [::1]:161
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6Transport().openServerMode(('::1', 161))
+ snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 161))
)
# SNMPv2c setup
# SecurityName <-> CommunityName mapping.
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Allow full MIB access for this user / securityModels at VACM
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py
index 7a7eadb..83080a0 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py
@@ -15,7 +15,7 @@ Either of the following Net-SNMP commands will walk this Agent:
| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6
| $ snmpwalk -v2c -c public 127.0.0.2 .1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -30,22 +30,24 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 161)),
)
# UDP over IPv4 at 127.0.0.2:161
config.addTransport(
snmpEngine,
udp.domainName + (2,),
- udp.UdpTransport().openServerMode(('127.0.0.2', 161))
+ udp.UdpTransport().openServerMode(("127.0.0.2", 161)),
)
# SNMPv2c setup
# SecurityName <-> CommunityName mapping.
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Allow full MIB access for this user / securityModels at VACM
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py b/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py
index dd270b6..97269ec 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py
@@ -31,7 +31,7 @@ address field.
To respond from a non-local (e.g. spoofed) IP address, uncomment the
.enableTransparent() method call and run this script as root.
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -42,7 +42,7 @@ snmpEngine = engine.SnmpEngine()
# Transport setup
# Initialize asyncore-based UDP/IPv4 transport
-udpSocketTransport = udp.UdpSocketTransport().openServerMode(('0.0.0.0', 161))
+udpSocketTransport = udp.UdpSocketTransport().openServerMode(("0.0.0.0", 161))
# Use sendmsg()/recvmsg() for socket communication (used for preserving
# original destination IP address when responding)
@@ -52,23 +52,24 @@ udpSocketTransport.enablePktInfo()
# udpSocketTransport.enableTransparent()
# Register this transport at SNMP Engine
-config.addTransport(
- snmpEngine,
- udp.domainName,
- udpSocketTransport
-)
+config.addTransport(snmpEngine, udp.domainName, udpSocketTransport)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py
index 005069a..f59a42a 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py
@@ -16,7 +16,7 @@ The following Net-SNMP's commands will GET/SET a value at this Agent:
| $ snmpget -v1 -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0
| $ snmpset -v1 -c private 127.0.0.1 SNMPv2-MIB::sysLocation.0 s "far away"
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -29,9 +29,7 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv1 setup
@@ -39,12 +37,19 @@ config.addTransport(
# SecurityName <-> CommunityName mapping.
# Here we configure two distinct CommunityName's to control read and write
# operations.
-config.addV1System(snmpEngine, 'my-read-area', 'public')
-config.addV1System(snmpEngine, 'my-write-area', 'private')
+config.addV1System(snmpEngine, "my-read-area", "public")
+config.addV1System(snmpEngine, "my-write-area", "private")
# Allow full MIB access for this user / securityModels at VACM
-config.addVacmUser(snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1))
-config.addVacmUser(snmpEngine, 1, 'my-write-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(snmpEngine, 1, "my-read-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine,
+ 1,
+ "my-write-area",
+ "noAuthNoPriv",
+ (1, 3, 6, 1, 2, 1),
+ (1, 3, 6, 1, 2, 1),
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py
index 6e81824..3c9416c 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py
@@ -24,7 +24,7 @@ Agent respectively:
Notice differently configured snmpEngineId's in usmUserEntry columns.
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.proto import rfc1902
@@ -33,8 +33,8 @@ from pysnmp.carrier.asyncore.dgram import udp
# Configuration parameters for each of SNMP Engines
snmpEngineInfo = (
- ('0102030405060708', udp.domainName + (0,), ('127.0.0.1', 161)),
- ('0807060504030201', udp.domainName + (1,), ('127.0.0.2', 161))
+ ("0102030405060708", udp.domainName + (0,), ("127.0.0.1", 161)),
+ ("0807060504030201", udp.domainName + (1,), ("127.0.0.2", 161)),
)
# Instantiate the single transport dispatcher object
@@ -43,7 +43,7 @@ transportDispatcher = AsyncoreDispatcher()
# Setup a custom data routing function to select snmpEngine by transportDomain
transportDispatcher.registerRoutingCbFun(lambda td, t, d: td)
-# Instantiate and configure SNMP Engines
+# Instantiate and configure SNMP Engines
for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo:
# Create SNMP engine with specific engineID
snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=snmpEngineId))
@@ -54,24 +54,27 @@ for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo:
# Transport setup
- # UDP over IPv4
+ # UDP over IPv4
config.addTransport(
- snmpEngine,
- transportDomain,
- udp.UdpTransport().openServerMode(transportAddress)
+ snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress)
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# Allow full MIB access for this user / securityModels at VACM
- config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6), (1, 3, 6, 1, 2, 1))
+ config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6), (1, 3, 6, 1, 2, 1)
+ )
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py
index 9d1454c..cda824c 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py
@@ -18,7 +18,7 @@ Either of the following Net-SNMP commands will walk this Agent:
| $ snmpwalk -v3 -u usr-sha-none -l authNoPriv -a SHA -A authkey1 localhost .1.3.6
| $ snmpwalk -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 localhost .1.3.6
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -30,35 +30,42 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 1161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 1161))
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# user: usr-sha-none, auth: SHA, priv NONE
-config.addV3User(
- snmpEngine, 'usr-sha-none',
- config.usmHMACSHAAuthProtocol, 'authkey1'
-)
+config.addV3User(snmpEngine, "usr-sha-none", config.usmHMACSHAAuthProtocol, "authkey1")
# user: usr-sha-none, auth: SHA, priv AES
config.addV3User(
- snmpEngine, 'usr-sha-aes128',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1'
+ snmpEngine,
+ "usr-sha-aes128",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
)
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
-config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
-config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
+config.addVacmUser(
+ snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
+config.addVacmUser(
+ snmpEngine, 3, "usr-sha-aes128", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py b/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py
index 5875107..a21c783 100644
--- a/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py
+++ b/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py
@@ -19,7 +19,7 @@ This script will report some details on request processing as seen
by rfc3412.receiveMessage() and rfc3412.returnResponsePdu()
abstract interfaces.
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
@@ -30,47 +30,56 @@ snmpEngine = engine.SnmpEngine()
# Execution point observer setup
-# Register a callback to be invoked at specified execution point of
+# Register a callback to be invoked at specified execution point of
# SNMP Engine and passed local variables at code point's local scope
# noinspection PyUnusedLocal,PyUnusedLocal
def requestObserver(snmpEngine, execpoint, variables, cbCtx):
- print('Execution point: %s' % execpoint)
- print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']]))
- print('* transportAddress: {} (local {})'.format('@'.join([str(x) for x in variables['transportAddress']]), '@'.join([str(x) for x in variables['transportAddress'].getLocalAddress()])))
- print('* securityModel: %s' % variables['securityModel'])
- print('* securityName: %s' % variables['securityName'])
- print('* securityLevel: %s' % variables['securityLevel'])
- print('* contextEngineId: %s' % variables['contextEngineId'].prettyPrint())
- print('* contextName: %s' % variables['contextName'].prettyPrint())
- print('* PDU: %s' % variables['pdu'].prettyPrint())
+ print("Execution point: %s" % execpoint)
+ print(
+ "* transportDomain: %s"
+ % ".".join([str(x) for x in variables["transportDomain"]])
+ )
+ print(
+ "* transportAddress: {} (local {})".format(
+ "@".join([str(x) for x in variables["transportAddress"]]),
+ "@".join([str(x) for x in variables["transportAddress"].getLocalAddress()]),
+ )
+ )
+ print("* securityModel: %s" % variables["securityModel"])
+ print("* securityName: %s" % variables["securityName"])
+ print("* securityLevel: %s" % variables["securityLevel"])
+ print("* contextEngineId: %s" % variables["contextEngineId"].prettyPrint())
+ print("* contextName: %s" % variables["contextName"].prettyPrint())
+ print("* PDU: %s" % variables["pdu"].prettyPrint())
snmpEngine.observer.registerObserver(
- requestObserver,
- 'rfc3412.receiveMessage:request',
- 'rfc3412.returnResponsePdu'
+ requestObserver, "rfc3412.receiveMessage:request", "rfc3412.returnResponsePdu"
)
# Transport setup
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161))
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# Allow full MIB access for each user at VACM
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
+config.addVacmUser(
+ snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)
+)
# Get default SNMP context this SNMP engine serves
snmpContext = context.SnmpContext(snmpEngine)
diff --git a/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py b/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py
index e860eea..1a49c44 100644
--- a/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py
+++ b/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py
@@ -22,7 +22,7 @@ Functionally similar to:
| $ snmpinform -v3 -l authPriv -u usr-md5-none -A authkey1 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification'
| $ snmpinform -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -34,84 +34,97 @@ snmpEngine = engine.SnmpEngine()
# SNMPv2c:
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds-1', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds-1", "my-area", "noAuthNoPriv", 1)
# SNMPv3:
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
-config.addTargetParams(snmpEngine, 'my-creds-2', 'usr-md5-none', 'authNoPriv')
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
+config.addTargetParams(snmpEngine, "my-creds-2", "usr-md5-none", "authNoPriv")
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
# First target
config.addTargetAddr(
- snmpEngine, 'my-nms-1',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds-1',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-1",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds-1",
+ tagList="all-my-managers",
)
# Second target
config.addTargetAddr(
- snmpEngine, 'my-nms-2',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds-2',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-2",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds-2",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "inform"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2&3), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
-config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
+config.addVacmUser(snmpEngine, 3, "usr-md5-none", "authNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
- print('Notification {}, status - {}'.format(sendRequestHandle,
- errorIndication and errorIndication or 'delivered'))
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
+ print(
+ "Notification {}, status - {}".format(
+ sendRequestHandle, errorIndication and errorIndication or "delivered"
+ )
+ )
# Build and submit notification message to dispatcher
sendRequestHandle = ntfOrg.sendVarBinds(
snmpEngine,
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator'))
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
],
- cbFun
+ cbFun,
)
-print('Notifications %s are scheduled to be sent' % sendRequestHandle)
+print("Notifications %s are scheduled to be sent" % sendRequestHandle)
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py b/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py
index 27f6274..c247dcb 100644
--- a/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py
+++ b/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py
@@ -15,9 +15,9 @@ framework for further treatment.
Functionally similar to:
-| $ snmptrap -v2c -c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1
+| $ snmptrap -v2c -c public localhost 0 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -27,24 +27,20 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
# Create named target
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds'
+ snmpEngine, "my-nms", udp.domainName, ("104.236.166.95", 162), "my-creds"
)
# *** SNMP engine configuration is complete by this line ***
@@ -55,39 +51,52 @@ v2c.apiTrapPDU.setDefaults(trapPDU)
# Set custom var-binds to TRAP PDU
v2c.apiTrapPDU.setVarBinds(
- trapPDU, [
+ trapPDU,
+ [
# sysUpTime
- (v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), v2c.TimeTicks(123)),
+ (v2c.ObjectIdentifier("1.3.6.1.2.1.1.3.0"), v2c.TimeTicks(123)),
# snmpTrapPDU
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)))
- ]
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
+ ],
)
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
- print('Notification {}, status - {}'.format(
- sendRequestHandle, errorIndication and errorIndication or 'delivered'
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
+ print(
+ "Notification {}, status - {}".format(
+ sendRequestHandle, errorIndication and errorIndication or "delivered"
+ )
)
- )
# Build and submit notification message to dispatcher
ntfOrg.sendPdu(
snmpEngine,
# Notification targets
- 'my-nms', # target address
- None, '', # contextEngineId, contextName
+ "my-nms", # target address
+ None,
+ "", # contextEngineId, contextName
trapPDU,
- cbFun
+ cbFun,
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py b/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py
index d43bc4a..8c10749 100644
--- a/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py
+++ b/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py
@@ -21,7 +21,7 @@ Functionally similar to:
| $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
| $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -31,74 +31,82 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
# First target
config.addTargetAddr(
- snmpEngine, 'my-nms-1',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-1",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Second target
config.addTargetAddr(
- snmpEngine, 'my-nms-2',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-2",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Third target
config.addTargetAddr(
- snmpEngine, 'my-nms-3',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-3",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
- ]
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
+ ],
)
-print('Notifications are scheduled to be sent')
+print("Notifications are scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py b/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py
index 65f557c..0587c7f 100644
--- a/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py
+++ b/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py
@@ -20,7 +20,7 @@ Functionally similar to:
| $ snmptrap -v2c -c public udp:104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
| $ snmptrap -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntforg
@@ -30,74 +30,78 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoints and bind it with security settings yielding
# a target name:
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms-1',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-1",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# UDP/IPv6
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6SocketTransport().openClientMode()
+ snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms-2',
- udp6.domainName, ('::1', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-2",
+ udp6.domainName,
+ ("::1", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
- ]
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
+ ],
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py b/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py
index 5b0f9f6..a93bff3 100644
--- a/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py
+++ b/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py
@@ -16,7 +16,7 @@ Functionally similar to:
| $ snmptrap -v1 -c public 104.236.166.95 1.3.6.1.6.3.1.1.5.1 0.0.0.0 1 0 0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -26,11 +26,10 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public',
- transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv1 -> 0)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
# Setup transport endpoint and bind it with security settings yielding
# a target name. Pay attention to the openClientMode() parameter -- it's
@@ -38,45 +37,51 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
config.addTransport(
snmpEngine,
udp.domainName,
- udp.UdpSocketTransport().openClientMode(iface=('0.0.0.0', 61024))
+ udp.UdpSocketTransport().openClientMode(iface=("0.0.0.0", 61024)),
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (1), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 1, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)))
- ]
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ )
+ ],
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and stop
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py b/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py
index c98d932..c496a3e 100644
--- a/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py
+++ b/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py
@@ -21,7 +21,7 @@ Functionally similar to:
| $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
| $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -31,73 +31,81 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
# First target
config.addTargetAddr(
- snmpEngine, 'my-nms-1',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-1",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Second target
config.addTargetAddr(
- snmpEngine, 'my-nms-2',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-2",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Third target
config.addTargetAddr(
- snmpEngine, 'my-nms-3',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-3",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM)
# to what targets (chosen by tag) and with what credentials.
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-creds', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-creds", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
- ]
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
+ ],
)
-print('Notifications are scheduled to be sent')
+print("Notifications are scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py b/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py
index d3478ac..6b1eb4e 100644
--- a/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py
+++ b/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py
@@ -7,16 +7,16 @@ Send SNMP INFORM notification using the following options:
* SNMPv3
* with user 'usr-md5-none', auth: MD5, priv NONE
* over IPv4/UDP
-* to a Manager at demo.snmplabs.com:162
+* to a Manager at localhost:162
* send INFORM notification
* with TRAP ID 'warmStart' specified as an OID
* include managed object information 1.3.6.1.2.1.1.5.0 = 'system name'
Functionally similar to:
-| $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name'
+| $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 localhost 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -26,66 +26,77 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# Add USM user
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
+config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv")
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "inform"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 3, "usr-md5-none", "authNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
- print('Notification {}, status - {}'.format(
- sendRequestHandle, errorIndication and errorIndication or 'delivered'
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
+ print(
+ "Notification {}, status - {}".format(
+ sendRequestHandle, errorIndication and errorIndication or "delivered"
+ )
)
- )
# Build and submit notification message to dispatcher
sendRequestHandle = ntfOrg.sendVarBinds(
snmpEngine,
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds: SNMPv2-MIB::coldStart, ...
- [((1, 3, 6, 1, 6, 3, 1, 1, 5, 1), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('system name'))],
- cbFun
+ [
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 5, 1),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("system name")),
+ ],
+ cbFun,
)
-print('Notification %s scheduled to be sent' % sendRequestHandle)
+print("Notification %s scheduled to be sent" % sendRequestHandle)
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/v1-trap.py b/examples/v3arch/asyncore/agent/ntforg/v1-trap.py
index 905993c..61ea497 100644
--- a/examples/v3arch/asyncore/agent/ntforg/v1-trap.py
+++ b/examples/v3arch/asyncore/agent/ntforg/v1-trap.py
@@ -18,9 +18,9 @@ Send SNMP notification using the following options:
Functionally similar to:
-| $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 104.236.166.95 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system"
+| $ snmptrap -v1 -c public localhost 1.3.6.1.4.1.20408.4.1.1.2 104.236.166.95 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system"
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -30,70 +30,72 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv1 -> 0)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (1), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 1, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# Uptime value with 12345
- (v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'),
- v2c.TimeTicks(12345)),
+ (v2c.ObjectIdentifier("1.3.6.1.2.1.1.3.0"), v2c.TimeTicks(12345)),
# trap OID: Generic Trap #6 (enterpriseSpecific)
# and Specific Trap 432
- (v2c.ObjectIdentifier('1.3.6.1.6.3.1.1.5.1'),
- v2c.ObjectIdentifier('1.3.6.1.4.1.20408.4.1.1.2.0.432')),
+ (
+ v2c.ObjectIdentifier("1.3.6.1.6.3.1.1.5.1"),
+ v2c.ObjectIdentifier("1.3.6.1.4.1.20408.4.1.1.2.0.432"),
+ ),
# Agent Address with '127.0.0.1'
- (v2c.ObjectIdentifier('1.3.6.1.6.3.18.1.3.0'),
- v2c.IpAddress('127.0.0.1')),
+ (v2c.ObjectIdentifier("1.3.6.1.6.3.18.1.3.0"), v2c.IpAddress("127.0.0.1")),
# Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2
- (v2c.ObjectIdentifier('1.3.6.1.6.3.1.1.4.3.0'),
- v2c.ObjectIdentifier('1.3.6.1.4.1.20408.4.1.1.2')),
+ (
+ v2c.ObjectIdentifier("1.3.6.1.6.3.1.1.4.3.0"),
+ v2c.ObjectIdentifier("1.3.6.1.4.1.20408.4.1.1.2"),
+ ),
# managed object '1.3.6.1.2.1.1.1.0' = 'my system'
- (v2c.ObjectIdentifier('1.3.6.1.2.1.1.1.0'),
- v2c.OctetString('my system'))
- ]
+ (v2c.ObjectIdentifier("1.3.6.1.2.1.1.1.0"), v2c.OctetString("my system")),
+ ],
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and stop
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py b/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py
index 240d375..ca4762b 100644
--- a/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py
+++ b/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py
@@ -18,7 +18,7 @@ Functionally similar to:
| $ snmpinform -v2c -c public 104.236.166.95 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example Notificator' 1.3.6.1.2.1.1.5.0 s 'Notificator Example'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -28,71 +28,82 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping (+ transport binding)
-config.addV1System(snmpEngine, 'my-area', 'public',
- transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "inform"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
- print('Notification {}, status - {}'.format(
- sendRequestHandle, errorIndication and errorIndication or 'delivered'
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
+ print(
+ "Notification {}, status - {}".format(
+ sendRequestHandle, errorIndication and errorIndication or "delivered"
+ )
)
- )
# Build and submit notification message to dispatcher
sendRequestHandle = ntfOrg.sendVarBinds(
snmpEngine,
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
],
- cbFun
+ cbFun,
)
-print('Notification %s scheduled to be sent' % sendRequestHandle)
+print("Notification %s scheduled to be sent" % sendRequestHandle)
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py b/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py
index 7ca6b0e..e62f21d 100644
--- a/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py
+++ b/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py
@@ -25,7 +25,7 @@ Functionally similar to:
| $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.3 IF-MIB::ifIndex."1" IF-MIB::ifAdminStatus."1" IF-MIB::ifOperStatus."1" IF-MIB::ifDescr."1"
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -39,10 +39,10 @@ from pysnmp.smi import rfc1902, view
#
instanceIndex = (1,)
objects = {
- ('IF-MIB', 'ifIndex'): instanceIndex[0],
- ('IF-MIB', 'ifAdminStatus'): 'up',
- ('IF-MIB', 'ifOperStatus'): 'down',
- ('IF-MIB', 'ifDescr'): 'eth0'
+ ("IF-MIB", "ifIndex"): instanceIndex[0],
+ ("IF-MIB", "ifAdminStatus"): "up",
+ ("IF-MIB", "ifOperStatus"): "down",
+ ("IF-MIB", "ifDescr"): "eth0",
}
# Create SNMP engine instance
@@ -52,57 +52,58 @@ snmpEngine = engine.SnmpEngine()
mibViewController = view.MibViewController(snmpEngine.getMibBuilder())
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoints and bind it with security settings yielding
# a target name:
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms-1',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms-1",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
rfc1902.NotificationType(
- rfc1902.ObjectIdentity('IF-MIB', 'linkUp'),
+ rfc1902.ObjectIdentity("IF-MIB", "linkUp"),
instanceIndex=instanceIndex,
- objects=objects
- ).resolveWithMib(mibViewController)
+ objects=objects,
+ ).resolveWithMib(mibViewController),
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py b/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py
index 02ea6e5..c4043c3 100644
--- a/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py
+++ b/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py
@@ -18,7 +18,7 @@ Functionally similar to:
| $ snmptrap -v2c -c public 104.236.166.95 12345 1.3.6.1.4.1.20408.4.1.1.2
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -28,71 +28,83 @@ from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers')
+config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers")
# Specify security settings per SecurityName (SNMPv2c -> 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
- print('Notification {}, status - {}'.format(
- sendRequestHandle, errorIndication and errorIndication or 'delivered'
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
+ print(
+ "Notification {}, status - {}".format(
+ sendRequestHandle, errorIndication and errorIndication or "delivered"
+ )
)
- )
# Build and submit notification message to dispatcher
sendRequestHandle = ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')),
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
+ ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")),
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
],
- cbFun
+ cbFun,
)
-print('Notification %s is scheduled to be sent' % sendRequestHandle)
+print("Notification %s is scheduled to be sent" % sendRequestHandle)
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/agent/ntforg/v3-trap.py b/examples/v3arch/asyncore/agent/ntforg/v3-trap.py
index 40b6e04..823deae 100644
--- a/examples/v3arch/asyncore/agent/ntforg/v3-trap.py
+++ b/examples/v3arch/asyncore/agent/ntforg/v3-trap.py
@@ -14,9 +14,9 @@ Send SNMP TRAP notification using the following options:
Functionally similar to:
-| $ snmptrap -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -e 8000000001020304 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s "my system"
+| $ snmptrap -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -e 8000000001020304 localhost 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s "my system"
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntforg
@@ -26,64 +26,71 @@ from pysnmp.proto.api import v2c
# SnmpEngineId -- it must also be known to the receiving party
# and configured at its VACM users table.
snmpEngine = engine.SnmpEngine(
- snmpEngineID=v2c.OctetString(hexValue='8000000001020304')
+ snmpEngineID=v2c.OctetString(hexValue="8000000001020304")
)
# Add USM user
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')
+config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv")
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-nms',
- udp.domainName, ('104.236.166.95', 162),
- 'my-creds',
- tagList='all-my-managers'
+ snmpEngine,
+ "my-nms",
+ udp.domainName,
+ ("104.236.166.95", 162),
+ "my-creds",
+ tagList="all-my-managers",
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
- snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
+ snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap"
)
# Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel
# and SecurityName
-config.addContext(snmpEngine, '')
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1, 3, 6))
+config.addContext(snmpEngine, "")
+config.addVacmUser(snmpEngine, 3, "usr-md5-des", "authPriv", (), (), (1, 3, 6))
# *** SNMP engine configuration is complete by this line ***
-# Create Notification Originator App instance.
+# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()
# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
snmpEngine,
# Notification targets
- 'my-notification', # notification targets
- None, '', # contextEngineId, contextName
+ "my-notification", # notification targets
+ None,
+ "", # contextEngineId, contextName
# var-binds
[
# SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart
- ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
+ (
+ (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
+ v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)),
+ ),
# additional var-binds: ( (oid, value), ... )
- ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example'))
- ]
+ ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")),
+ ],
)
-print('Notification is scheduled to be sent')
+print("Notification is scheduled to be sent")
# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()
diff --git a/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py b/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py
index 944598a..e366c35 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py
@@ -16,7 +16,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -E 80004fb805636c6f75644dab22cc -n da761cfc8c94d3aceef4f60f049105ba -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -30,11 +30,8 @@ snmpEngine = engine.SnmpEngine()
#
# user: usr-md5-none, auth: MD5, priv: NONE
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
+config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -43,41 +40,48 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message, pass custom ContextEngineId & ContextName
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
+ "my-router",
# contextEngineId
- rfc1902.OctetString(hexValue='80004fb805636c6f75644dab22cc'),
+ rfc1902.OctetString(hexValue="80004fb805636c6f75644dab22cc"),
# contextName
- rfc1902.OctetString('da761cfc8c94d3aceef4f60f049105ba'),
+ rfc1902.OctetString("da761cfc8c94d3aceef4f60f049105ba"),
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py b/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py
index adf4d54..58dfc9b 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py
@@ -14,7 +14,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v2c -c public -ObentU -r 5 -t 1 104.236.166.95 1.3.6.1.2.1.1.1.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -27,52 +27,64 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
#
# Setup transport endpoint and bind it with security settings yielding
-# a target name
+# a target name
#
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds',
+ snmpEngine,
+ "my-router",
+ udp.domainName,
+ ("104.236.166.95", 161),
+ "my-creds",
timeout=300, # in 1/100 sec
- retryCount=5
+ retryCount=5,
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py b/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py
index a22a2c4..ec71ba8 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py
@@ -14,7 +14,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpwalk -v3 -l authNoPriv -u usr-md5-none -A authkey1 -ObentU udp6:[::1]:161 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp6
from pysnmp.entity.rfc3413 import cmdgen
@@ -27,11 +27,8 @@ snmpEngine = engine.SnmpEngine()
#
# user: usr-md5-des, auth: MD5, priv NONE
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
+config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -40,42 +37,47 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
# UDP/IPv6
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6SocketTransport().openClientMode()
-)
-config.addTargetAddr(
- snmpEngine, 'my-router',
- udp6.domainName, ('::1', 161),
- 'my-creds'
+ snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode()
)
+config.addTargetAddr(snmpEngine, "my-router", udp6.domainName, ("::1", 161), "my-creds")
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return
if errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return True # signal dispatcher to continue
# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [((1, 3, 6, 1, 2, 1, 1), None),
- ((1, 3, 6, 1, 4, 1, 1), None)],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py
index 3deaa8b..9df83b4 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py
@@ -15,7 +15,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpbulkwalk -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -C n1 -C r25 -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdgen
from pysnmp.carrier.asyncore.dgram import udp
@@ -29,11 +29,14 @@ snmpEngine = engine.SnmpEngine()
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')
+config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -42,43 +45,51 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequesthandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequesthandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return # stop on error
if errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return True # signal dispatcher to continue walking
# Prepare initial request to be sent
cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- 0, 25, # non-repeaters, max-repetitions
- (((1, 3, 6, 1, 2, 1, 1), None),
- ((1, 3, 6, 1, 4, 1, 1), None)),
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ 0,
+ 25, # non-repeaters, max-repetitions
+ (((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)),
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py
index e13470b..b5c496a 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py
@@ -14,7 +14,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpbulkwalk -v2c -c public -C n0 -C r25 -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdgen
from pysnmp.carrier.asyncore.dgram import udp
@@ -27,10 +27,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -39,43 +39,51 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequesthandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequesthandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return # stop on error
if errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return True # signal dispatcher to continue walking
# Prepare initial request to be sent
cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- 0, 25, # non-repeaters, max-repetitions
- [((1, 3, 6, 1, 2, 1, 1), None),
- ((1, 3, 6, 1, 4, 1, 1), None)],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ 0,
+ 25, # non-repeaters, max-repetitions
+ [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py
index cb0e7c4..f4608c7 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py
@@ -14,7 +14,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpwalk -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -32,16 +32,16 @@ compiler.addMibCompiler(snmpEngine.getMibBuilder())
# Used for MIB objects resolution
mibViewController = view.MibViewController(snmpEngine.getMibBuilder())
-#
+#
#
# SNMPv1/2c setup
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -50,45 +50,62 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
if errorStatus and errorStatus != 2:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for varBind in varBindRow:
- print(rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]),
- varBind[1]).resolveWithMib(mibViewController).prettyPrint())
+ print(
+ rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1])
+ .resolveWithMib(mibViewController)
+ .prettyPrint()
+ )
return 1 # signal dispatcher to continue
# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [rfc1902.ObjectType(rfc1902.ObjectIdentity('iso.org.dod')).resolveWithMib(mibViewController),
- rfc1902.ObjectType(rfc1902.ObjectIdentity('IF-MIB', 'ifMIB')).resolveWithMib(mibViewController)],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [
+ rfc1902.ObjectType(rfc1902.ObjectIdentity("iso.org.dod")).resolveWithMib(
+ mibViewController
+ ),
+ rfc1902.ObjectType(rfc1902.ObjectIdentity("IF-MIB", "ifMIB")).resolveWithMib(
+ mibViewController
+ ),
+ ],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py
index f7f0df1..21a7941 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py
@@ -14,7 +14,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpwalk -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -27,10 +27,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -39,44 +39,51 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
if errorStatus and errorStatus != 2:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return 1 # signal dispatcher to continue
# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [((1, 3, 6, 1, 2, 1, 1), None),
- ((1, 3, 6, 1, 4, 1, 1), None)],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py b/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py
index eaa6efa..76a7be7 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py
@@ -17,7 +17,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -28,25 +28,35 @@ snmpEngine = engine.SnmpEngine()
# Execution point observer setup
-# Register a callback to be invoked at specified execution point of
+# Register a callback to be invoked at specified execution point of
# SNMP Engine and passed local variables at code point's local scope
# noinspection PyUnusedLocal,PyUnusedLocal
def requestObserver(snmpEngine, execpoint, variables, cbCtx):
- print('Execution point: %s' % execpoint)
- print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']]))
- print('* transportAddress: %s' % '@'.join([str(x) for x in variables['transportAddress']]))
- print('* securityModel: %s' % variables['securityModel'])
- print('* securityName: %s' % variables['securityName'])
- print('* securityLevel: %s' % variables['securityLevel'])
- print('* contextEngineId: {}'.format(variables['contextEngineId'] and variables['contextEngineId'].prettyPrint() or '<empty>'))
- print('* contextName: %s' % variables['contextName'].prettyPrint())
- print('* PDU: %s' % variables['pdu'].prettyPrint())
+ print("Execution point: %s" % execpoint)
+ print(
+ "* transportDomain: %s"
+ % ".".join([str(x) for x in variables["transportDomain"]])
+ )
+ print(
+ "* transportAddress: %s"
+ % "@".join([str(x) for x in variables["transportAddress"]])
+ )
+ print("* securityModel: %s" % variables["securityModel"])
+ print("* securityName: %s" % variables["securityName"])
+ print("* securityLevel: %s" % variables["securityLevel"])
+ print(
+ "* contextEngineId: {}".format(
+ variables["contextEngineId"]
+ and variables["contextEngineId"].prettyPrint()
+ or "<empty>"
+ )
+ )
+ print("* contextName: %s" % variables["contextName"].prettyPrint())
+ print("* PDU: %s" % variables["pdu"].prettyPrint())
snmpEngine.observer.registerObserver(
- requestObserver,
- 'rfc3412.sendPdu',
- 'rfc3412.receiveMessage:response'
+ requestObserver, "rfc3412.sendPdu", "rfc3412.receiveMessage:response"
)
#
@@ -55,11 +65,14 @@ snmpEngine.observer.registerObserver(
# user: usr-sha-aes, auth: SHA, priv AES
config.addV3User(
- snmpEngine, 'usr-sha-aes',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1'
+ snmpEngine,
+ "usr-sha-aes",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv')
+config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -68,38 +81,46 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py b/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py
index 0d5d581..0f2f72d 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py
@@ -13,14 +13,14 @@ This script performs similar to the following Net-SNMP command:
| $ snmpwalk -v3 -l noAuthNoPriv -u usr-none-none -ObentU 104.236.166.95:161 1.3.6.1.2.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
from pysnmp.proto import rfc1902
# Initial OID prefix
-initialOID = rfc1902.ObjectName('1.3.6.1.2.1.1')
+initialOID = rfc1902.ObjectName("1.3.6.1.2.1.1")
# Create SNMP engine instance
snmpEngine = engine.SnmpEngine()
@@ -31,9 +31,10 @@ snmpEngine = engine.SnmpEngine()
# user: usr-none-none, auth: none, priv: none
config.addV3User(
- snmpEngine, 'usr-none-none',
+ snmpEngine,
+ "usr-none-none",
)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv')
+config.addTargetParams(snmpEngine, "my-creds", "usr-none-none", "noAuthNoPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -42,32 +43,39 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return
if errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
if initialOID.isPrefixOf(oid):
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
else:
return False # signal dispatcher to stop
return True # signal dispatcher to continue
@@ -76,10 +84,11 @@ def cbFun(snmpEngine, sendRequestHandle, errorIndication,
# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[(initialOID, None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py b/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py
index db927af..4c23018 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py
@@ -15,7 +15,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpwalk -v2c -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -28,10 +28,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -42,40 +42,49 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
config.addTransport(
snmpEngine,
udp.domainName,
- udp.UdpSocketTransport().openClientMode(('0.0.0.0', 61024))
+ udp.UdpSocketTransport().openClientMode(("0.0.0.0", 61024)),
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBindTable, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBindTable,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
return
if errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?",
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
return 1 # signal dispatcher to continue
# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [((1, 3, 6, 1, 2, 1, 1), None),
- ((1, 3, 6, 1, 2, 1, 11), None)],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 2, 1, 11), None)],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py b/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py
index 7994c53..0dbba32 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py
@@ -13,7 +13,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpset -v1 -c private -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s 'my value' 1.3.6.1.2.1.1.9.1.4.1 t 123
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -27,10 +27,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'private')
+config.addV1System(snmpEngine, "my-area", "private")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -39,41 +39,51 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
elif errorStatus and errorStatus != 2:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString('my value')),
- ((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [
+ ((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString("my value")),
+ ((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123)),
+ ],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py b/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py
index 3e7ed93..5b4ed24 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py
@@ -22,7 +22,7 @@ Superuser privileges are only required to send spoofed packets.
Alternatively, sending from local interface could also be achieved by
binding to it (via openClientMode() parameter).
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -35,10 +35,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -56,44 +56,54 @@ udpSocketTransport.enablePktInfo()
udpSocketTransport.enableTransparent()
# Register this transport at SNMP Engine
-config.addTransport(
- snmpEngine,
- udp.domainName,
- udpSocketTransport
-)
+config.addTransport(snmpEngine, udp.domainName, udpSocketTransport)
# Configure destination IPv4 address as well as source IPv4 address
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds',
- sourceAddress=('1.2.3.4', 0)
+ snmpEngine,
+ "my-router",
+ udp.domainName,
+ ("104.236.166.95", 161),
+ "my-creds",
+ sourceAddress=("1.2.3.4", 0),
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
elif errorStatus and errorStatus != 2:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py
index 43f11e9..96e93e4 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py
@@ -12,7 +12,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -26,11 +26,14 @@ snmpEngine = engine.SnmpEngine()
# user: usr-sha-aes, auth: SHA, priv AES
config.addV3User(
- snmpEngine, 'usr-sha-aes',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1'
+ snmpEngine,
+ "usr-sha-aes",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv')
+config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -39,44 +42,49 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
-config.delTransport(
- snmpEngine,
- udp.domainName
-).closeTransport()
+config.delTransport(snmpEngine, udp.domainName).closeTransport()
diff --git a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py
index 9a29ec5..d4ecfa0 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py
@@ -13,7 +13,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpset -v3 -l authNoPriv -u usr-sha-none -a SHA -A authkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s 'my new value'
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -27,11 +27,8 @@ snmpEngine = engine.SnmpEngine()
#
# user: usr-sha-none, auth: SHA, priv none
-config.addV3User(
- snmpEngine, 'usr-sha-none',
- config.usmHMACSHAAuthProtocol, 'authkey1'
-)
-config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-none', 'authNoPriv')
+config.addV3User(snmpEngine, "usr-sha-none", config.usmHMACSHAAuthProtocol, "authkey1")
+config.addTargetParams(snmpEngine, "my-creds", "usr-sha-none", "authNoPriv")
#
# Setup transport endpoint and bind it with security settings yielding
@@ -40,38 +37,46 @@ config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-none', 'authNoPriv')
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
- [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString('my new value'))],
- cbFun
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
+ [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString("my new value"))],
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/v1-get.py b/examples/v3arch/asyncore/manager/cmdgen/v1-get.py
index 4bdf84e..e9f5b00 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/v1-get.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/v1-get.py
@@ -11,7 +11,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpget -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -24,10 +24,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -36,40 +36,48 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
elif errorStatus and errorStatus != 2:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 1, 0), None)],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py b/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py
index 9edb2be..8361d13 100644
--- a/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py
+++ b/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py
@@ -12,7 +12,7 @@ This script performs similar to the following Net-SNMP command:
| $ snmpset -v2c -c private -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.4.1 t 123
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import cmdgen
@@ -26,10 +26,10 @@ snmpEngine = engine.SnmpEngine()
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'private')
+config.addV1System(snmpEngine, "my-area", "private")
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
+config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1)
#
# Setup transport endpoint and bind it with security settings yielding
@@ -38,38 +38,46 @@ config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
# UDP/IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpSocketTransport().openClientMode()
+ snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
- snmpEngine, 'my-router',
- udp.domainName, ('104.236.166.95', 161),
- 'my-creds'
+ snmpEngine, "my-router", udp.domainName, ("104.236.166.95", 161), "my-creds"
)
# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds, cbCtx):
+def cbFun(
+ snmpEngine,
+ sendRequestHandle,
+ errorIndication,
+ errorStatus,
+ errorIndex,
+ varBinds,
+ cbCtx,
+):
if errorIndication:
print(errorIndication)
elif errorStatus:
- print('{} at {}'.format(errorStatus.prettyPrint(),
- errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
+ print(
+ "{} at {}".format(
+ errorStatus.prettyPrint(),
+ errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
+ )
+ )
else:
for oid, val in varBinds:
- print(f'{oid.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{oid.prettyPrint()} = {val.prettyPrint()}")
# Prepare and send a request message
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine,
- 'my-router',
- None, '', # contextEngineId, contextName
+ "my-router",
+ None,
+ "", # contextEngineId, contextName
[((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))],
- cbFun
+ cbFun,
)
# Run I/O dispatcher which would send pending queries and process responses
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py b/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py
index 73e9501..7fda0fd 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py
@@ -15,7 +15,7 @@ receiver:
| $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
@@ -30,30 +30,33 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 162)),
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
# Get an execution context...
execContext = snmpEngine.observer.getExecutionContext(
- 'rfc3412.receiveMessage:request'
+ "rfc3412.receiveMessage:request"
)
# ... and use inner SNMP engine data to figure out peer address
- print('Notification from {}, ContextEngineId "{}", ContextName "{}"'.format('@'.join([str(x) for x in execContext['transportAddress']]),
- contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+ print(
+ 'Notification from {}, ContextEngineId "{}", ContextName "{}"'.format(
+ "@".join([str(x) for x in execContext["transportAddress"]]),
+ contextEngineId.prettyPrint(),
+ contextName.prettyPrint(),
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py
index 7390712..4b6c608 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py
@@ -16,7 +16,7 @@ receiver:
| $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test
| $ snmpinform -v2c -c public 127.0.0.1:2162 123 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
@@ -31,30 +31,32 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 162)),
)
# UDP over IPv4, second listening interface/port
config.addTransport(
snmpEngine,
udp.domainName + (2,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 2162))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 2162)),
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
- print('Notification from ContextEngineId "{}", ContextName "{}"'.format(contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ print(
+ 'Notification from ContextEngineId "{}", ContextName "{}"'.format(
+ contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py
index 5d97c99..de6c2ce 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py
@@ -17,7 +17,7 @@ receiver:
| $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test
| $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntfrcv
@@ -30,32 +30,30 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162))
)
# UDP over IPv6
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6Transport().openServerMode(('::1', 162))
+ snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 162))
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
- print('Notification from ContextEngineId "{}", ContextName "{}"'.format(contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ print(
+ 'Notification from ContextEngineId "{}", ContextName "{}"'.format(
+ contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py
index fb96533..b07d224 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py
@@ -21,7 +21,7 @@ receiver:
| $ snmptrap -v3 -u usr-md5-none -l authNoPriv -A authkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1
| $ snmpinform -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
@@ -35,67 +35,78 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162))
)
# SNMPv3/USM setup
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
# user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304
# this USM entry is used for TRAP receiving purposes
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1',
- securityEngineId=v2c.OctetString(hexValue='8000000001020304')
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
+ securityEngineId=v2c.OctetString(hexValue="8000000001020304"),
)
# user: usr-md5-none, auth: MD5, priv NONE
-config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1'
-)
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
# user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304
# this USM entry is used for TRAP receiving purposes
config.addV3User(
- snmpEngine, 'usr-md5-none',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- securityEngineId=v2c.OctetString(hexValue='8000000001020304')
+ snmpEngine,
+ "usr-md5-none",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ securityEngineId=v2c.OctetString(hexValue="8000000001020304"),
)
# user: usr-sha-aes128, auth: SHA, priv AES
config.addV3User(
- snmpEngine, 'usr-sha-aes128',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1'
+ snmpEngine,
+ "usr-sha-aes128",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
)
# user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304
# this USM entry is used for TRAP receiving purposes
config.addV3User(
- snmpEngine, 'usr-sha-aes128',
- config.usmHMACSHAAuthProtocol, 'authkey1',
- config.usmAesCfb128Protocol, 'privkey1',
- securityEngineId=v2c.OctetString(hexValue='8000000001020304')
+ snmpEngine,
+ "usr-sha-aes128",
+ config.usmHMACSHAAuthProtocol,
+ "authkey1",
+ config.usmAesCfb128Protocol,
+ "privkey1",
+ securityEngineId=v2c.OctetString(hexValue="8000000001020304"),
)
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
- print('Notification from ContextEngineId "{}", ContextName "{}"'.format(contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ print(
+ 'Notification from ContextEngineId "{}", ContextName "{}"'.format(
+ contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py b/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py
index 7985596..d83bf34 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py
@@ -18,7 +18,7 @@ receiver:
| $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test
| $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntfrcv
@@ -30,57 +30,59 @@ snmpEngine = engine.SnmpEngine()
# Execution point observer setup
-# Register a callback to be invoked at specified execution point of
+# Register a callback to be invoked at specified execution point of
# SNMP Engine and passed local variables at code point's local scope
# noinspection PyUnusedLocal,PyUnusedLocal
def requestObserver(snmpEngine, execpoint, variables, cbCtx):
- print('Execution point: %s' % execpoint)
- print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']]))
- print('* transportAddress: %s' % '@'.join([str(x) for x in variables['transportAddress']]))
- print('* securityModel: %s' % variables['securityModel'])
- print('* securityName: %s' % variables['securityName'])
- print('* securityLevel: %s' % variables['securityLevel'])
- print('* contextEngineId: %s' % variables['contextEngineId'].prettyPrint())
- print('* contextName: %s' % variables['contextName'].prettyPrint())
- print('* PDU: %s' % variables['pdu'].prettyPrint())
+ print("Execution point: %s" % execpoint)
+ print(
+ "* transportDomain: %s"
+ % ".".join([str(x) for x in variables["transportDomain"]])
+ )
+ print(
+ "* transportAddress: %s"
+ % "@".join([str(x) for x in variables["transportAddress"]])
+ )
+ print("* securityModel: %s" % variables["securityModel"])
+ print("* securityName: %s" % variables["securityName"])
+ print("* securityLevel: %s" % variables["securityLevel"])
+ print("* contextEngineId: %s" % variables["contextEngineId"].prettyPrint())
+ print("* contextName: %s" % variables["contextName"].prettyPrint())
+ print("* PDU: %s" % variables["pdu"].prettyPrint())
snmpEngine.observer.registerObserver(
- requestObserver,
- 'rfc3412.receiveMessage:request',
- 'rfc3412.returnResponsePdu'
+ requestObserver, "rfc3412.receiveMessage:request", "rfc3412.returnResponsePdu"
)
# Transport setup
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162))
)
# UDP over IPv6
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6Transport().openServerMode(('::1', 162))
+ snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 162))
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
- print('Notification from ContextEngineId "{}", ContextName "{}"'.format(contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ print(
+ 'Notification from ContextEngineId "{}", ContextName "{}"'.format(
+ contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py b/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py
index f28bfe7..58bbd18 100644
--- a/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py
+++ b/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py
@@ -24,7 +24,7 @@ Engine, and may modify it to match the only locally configured CommunityName
'public'. This effectively makes NotificationReceiver accepting messages with
CommunityName's, not explicitly configured to local SNMP Engine.
-"""#
+""" #
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
@@ -42,39 +42,43 @@ snmpEngine = engine.SnmpEngine()
# selection.
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def requestObserver(snmpEngine, execpoint, variables, cbCtx):
- if re.match('.*love.*', str(variables['communityName'])):
- print('Rewriting communityName \'{}\' from {} into \'public\''.format(variables['communityName'], ':'.join([str(x) for x in variables['transportInformation'][1]])))
- variables['communityName'] = variables['communityName'].clone('public')
+ if re.match(".*love.*", str(variables["communityName"])):
+ print(
+ "Rewriting communityName '{}' from {} into 'public'".format(
+ variables["communityName"],
+ ":".join([str(x) for x in variables["transportInformation"][1]]),
+ )
+ )
+ variables["communityName"] = variables["communityName"].clone("public")
snmpEngine.observer.registerObserver(
- requestObserver,
- 'rfc2576.processIncomingMsg:writable'
+ requestObserver, "rfc2576.processIncomingMsg:writable"
)
# Transport setup
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openServerMode(('127.0.0.1', 162))
+ snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162))
)
# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
-def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
- varBinds, cbCtx):
- print('Notification from ContextEngineId "{}", ContextName "{}"'.format(contextEngineId.prettyPrint(),
- contextName.prettyPrint()))
+def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
+ print(
+ 'Notification from ContextEngineId "{}", ContextName "{}"'.format(
+ contextEngineId.prettyPrint(), contextName.prettyPrint()
+ )
+ )
for name, val in varBinds:
- print(f'{name.prettyPrint()} = {val.prettyPrint()}')
+ print(f"{name.prettyPrint()} = {val.prettyPrint()}")
# Register SNMP Application at the SNMP engine
diff --git a/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py b/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py
index 9e34fd0..5663125 100644
--- a/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py
+++ b/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py
@@ -23,7 +23,7 @@ so that it will re-map possible duplicate request-ID values, coming in
initial request PDUs from different Managers, into unique values to
avoid sending duplicate request-IDs to Agents.
-"""#
+""" #
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context
@@ -42,26 +42,20 @@ snmpEngine = engine.SnmpEngine()
# UDP over IPv6
config.addTransport(
- snmpEngine,
- udp6.domainName,
- udp6.Udp6Transport().openServerMode(('::1', 161))
+ snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 161))
)
# Manager section
# UDP over IPv4
-config.addTransport(
- snmpEngine,
- udp.domainName,
- udp.UdpTransport().openClientMode()
-)
+config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openClientMode())
#
# SNMPv1/2c setup (Agent role)
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, '1-my-area', 'public')
+config.addV1System(snmpEngine, "1-my-area", "public")
#
# SNMPv1/v2c setup (Manager role)
@@ -70,23 +64,27 @@ config.addV1System(snmpEngine, '1-my-area', 'public')
# to let it match first in snmpCommunityTable on response processing.
#
-config.addV1System(snmpEngine, '0-distant-area', 'public', transportTag='remote')
+config.addV1System(snmpEngine, "0-distant-area", "public", transportTag="remote")
#
# Transport target used by Manager
#
config.addTargetParams(
- snmpEngine, 'distant-agent-auth', '0-distant-area', 'noAuthNoPriv', 1
+ snmpEngine, "distant-agent-auth", "0-distant-area", "noAuthNoPriv", 1
)
config.addTargetAddr(
- snmpEngine, 'distant-agent',
- udp.domainName, ('104.236.166.95', 161),
- 'distant-agent-auth', retryCount=0, tagList='remote'
+ snmpEngine,
+ "distant-agent",
+ udp.domainName,
+ ("104.236.166.95", 161),
+ "distant-agent-auth",
+ retryCount=0,
+ tagList="remote",
)
# Default SNMP context
-config.addContext(snmpEngine, '')
+config.addContext(snmpEngine, "")
class CommandResponder(cmdrsp.CommandResponderBase):
@@ -94,40 +92,39 @@ class CommandResponder(cmdrsp.CommandResponderBase):
v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
- v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
+ v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(),
}
pduTypes = cmdGenMap.keys() # This app will handle these PDUs
# SNMP request relay
- def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
- PDU, acInfo):
+ def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo):
cbCtx = stateReference, PDU
contextEngineId = None # address authoritative SNMP Engine
try:
self.cmdGenMap[PDU.tagSet].sendPdu(
- snmpEngine, 'distant-agent',
- contextEngineId, contextName,
+ snmpEngine,
+ "distant-agent",
+ contextEngineId,
+ contextName,
PDU,
- self.handleResponsePdu, cbCtx
+ self.handleResponsePdu,
+ cbCtx,
)
except error.PySnmpError:
- self.handleResponsePdu(
- snmpEngine, stateReference, 'error', None, cbCtx
- )
+ self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx)
# SNMP response relay
# noinspection PyUnusedLocal
- def handleResponsePdu(self, snmpEngine, sendRequestHandle,
- errorIndication, PDU, cbCtx):
+ def handleResponsePdu(
+ self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx
+ ):
stateReference, reqPDU = cbCtx
if errorIndication:
PDU = v2c.apiPDU.getResponse(reqPDU)
PDU.setErrorStatus(PDU, 5)
- self.sendPdu(
- snmpEngine, stateReference, PDU
- )
+ self.sendPdu(snmpEngine, stateReference, PDU)
self.releaseStateInformation(stateReference)
diff --git a/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py b/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py
index 3dd64dd..5ca1eac 100644
--- a/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py
+++ b/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py
@@ -23,7 +23,7 @@ so that it will re-map possible duplicate request-ID values, coming in
initial request PDUs from different Managers, into unique values to
avoid sending duplicate request-IDs to Agents.
-"""#
+""" #
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context
@@ -44,16 +44,14 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 161)),
)
# Manager section
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName + (2,),
- udp.UdpTransport().openClientMode()
+ snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode()
)
#
@@ -61,31 +59,36 @@ config.addTransport(
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
#
# SNMPv1 setup (Manager role)
#
# SecurityName <-> CommunityName <-> Transport mapping
-config.addV1System(snmpEngine, 'distant-area', 'public', transportTag='distant')
+config.addV1System(snmpEngine, "distant-area", "public", transportTag="distant")
#
# Transport target used by Manager
#
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'distant-agent-auth', 'distant-area',
- 'noAuthNoPriv', 0)
+config.addTargetParams(
+ snmpEngine, "distant-agent-auth", "distant-area", "noAuthNoPriv", 0
+)
config.addTargetAddr(
- snmpEngine, 'distant-agent',
- udp.domainName + (2,), ('104.236.166.95', 161),
- 'distant-agent-auth', retryCount=0, tagList='distant'
+ snmpEngine,
+ "distant-agent",
+ udp.domainName + (2,),
+ ("104.236.166.95", 161),
+ "distant-agent-auth",
+ retryCount=0,
+ tagList="distant",
)
# Default SNMP context
-config.addContext(snmpEngine, '')
+config.addContext(snmpEngine, "")
class CommandResponder(cmdrsp.CommandResponderBase):
@@ -93,40 +96,39 @@ class CommandResponder(cmdrsp.CommandResponderBase):
v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
- v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
+ v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(),
}
pduTypes = cmdGenMap.keys() # This app will handle these PDUs
# SNMP request relay
- def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
- PDU, acInfo):
+ def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo):
cbCtx = stateReference, PDU
contextEngineId = None # address authoritative SNMP Engine
try:
self.cmdGenMap[PDU.tagSet].sendPdu(
- snmpEngine, 'distant-agent',
- contextEngineId, contextName,
+ snmpEngine,
+ "distant-agent",
+ contextEngineId,
+ contextName,
PDU,
- self.handleResponsePdu, cbCtx
+ self.handleResponsePdu,
+ cbCtx,
)
except error.PySnmpError:
- self.handleResponsePdu(
- snmpEngine, stateReference, 'error', None, cbCtx
- )
+ self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx)
# SNMP response relay
# noinspection PyUnusedLocal
- def handleResponsePdu(self, snmpEngine, sendRequestHandle,
- errorIndication, PDU, cbCtx):
+ def handleResponsePdu(
+ self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx
+ ):
stateReference, reqPDU = cbCtx
if errorIndication:
PDU = v2c.apiPDU.getResponse(reqPDU)
PDU.setErrorStatus(PDU, 5)
- self.sendPdu(
- snmpEngine, stateReference, PDU
- )
+ self.sendPdu(snmpEngine, stateReference, PDU)
self.releaseStateInformation(stateReference)
diff --git a/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py b/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py
index f5d6167..a91352c 100644
--- a/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py
+++ b/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py
@@ -22,7 +22,7 @@ so that it will re-map possible duplicate request-ID values, coming in
initial request PDUs from different Managers, into unique values to
avoid sending duplicate request-IDs to Agents.
-"""#
+""" #
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context
@@ -43,16 +43,14 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 161)),
)
# Manager section
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName + (2,),
- udp.UdpTransport().openClientMode()
+ snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode()
)
#
@@ -60,32 +58,31 @@ config.addTransport(
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
#
# SNMPv3/USM setup (Manager role)
#
# user: usr-md5-none, auth: MD5, priv NONE
-config.addV3User(
- snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1'
-)
+config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1")
#
# Transport target used by Manager
#
-config.addTargetParams(
- snmpEngine, 'distant-agent-auth', 'usr-md5-none', 'authNoPriv'
-)
+config.addTargetParams(snmpEngine, "distant-agent-auth", "usr-md5-none", "authNoPriv")
config.addTargetAddr(
- snmpEngine, 'distant-agent',
- udp.domainName + (2,), ('104.236.166.95', 161),
- 'distant-agent-auth', retryCount=0
+ snmpEngine,
+ "distant-agent",
+ udp.domainName + (2,),
+ ("104.236.166.95", 161),
+ "distant-agent-auth",
+ retryCount=0,
)
# Default SNMP context
-config.addContext(snmpEngine, '')
+config.addContext(snmpEngine, "")
class CommandResponder(cmdrsp.CommandResponderBase):
@@ -93,40 +90,39 @@ class CommandResponder(cmdrsp.CommandResponderBase):
v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
- v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
+ v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(),
}
pduTypes = cmdGenMap.keys() # This app will handle these PDUs
# SNMP request relay
- def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
- PDU, acInfo):
+ def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo):
cbCtx = stateReference, PDU
contextEngineId = None # address authoritative SNMP Engine
try:
self.cmdGenMap[PDU.tagSet].sendPdu(
- snmpEngine, 'distant-agent',
- contextEngineId, contextName,
+ snmpEngine,
+ "distant-agent",
+ contextEngineId,
+ contextName,
PDU,
- self.handleResponsePdu, cbCtx
+ self.handleResponsePdu,
+ cbCtx,
)
except error.PySnmpError:
- self.handleResponsePdu(
- snmpEngine, stateReference, 'error', None, cbCtx
- )
+ self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx)
# SNMP response relay
# noinspection PyUnusedLocal
- def handleResponsePdu(self, snmpEngine, sendRequestHandle,
- errorIndication, PDU, cbCtx):
+ def handleResponsePdu(
+ self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx
+ ):
stateReference, reqPDU = cbCtx
if errorIndication:
PDU = v2c.apiPDU.getResponse(reqPDU)
PDU.setErrorStatus(PDU, 5)
- self.sendPdu(
- snmpEngine, stateReference, PDU
- )
+ self.sendPdu(snmpEngine, stateReference, PDU)
self.releaseStateInformation(stateReference)
diff --git a/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py b/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py
index b5d6479..f2e2bd7 100644
--- a/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py
+++ b/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py
@@ -22,7 +22,7 @@ so that it will re-map possible duplicate request-ID values, coming in
initial request PDUs from different Managers, into unique values to
avoid sending duplicate request-IDs to Agents.
-"""#
+""" #
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context
@@ -43,16 +43,14 @@ snmpEngine = engine.SnmpEngine()
config.addTransport(
snmpEngine,
udp.domainName + (1,),
- udp.UdpTransport().openServerMode(('127.0.0.1', 161))
+ udp.UdpTransport().openServerMode(("127.0.0.1", 161)),
)
# Manager section
# UDP over IPv4
config.addTransport(
- snmpEngine,
- udp.domainName + (2,),
- udp.UdpTransport().openClientMode()
+ snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode()
)
#
@@ -61,9 +59,12 @@ config.addTransport(
# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
- snmpEngine, 'usr-md5-des',
- config.usmHMACMD5AuthProtocol, 'authkey1',
- config.usmDESPrivProtocol, 'privkey1'
+ snmpEngine,
+ "usr-md5-des",
+ config.usmHMACMD5AuthProtocol,
+ "authkey1",
+ config.usmDESPrivProtocol,
+ "privkey1",
)
#
@@ -71,24 +72,26 @@ config.addV3User(
#
# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
+config.addV1System(snmpEngine, "my-area", "public")
#
# Transport target used by Manager
#
# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-config.addTargetParams(snmpEngine, 'distant-agent-auth', 'my-area',
- 'noAuthNoPriv', 0)
+config.addTargetParams(snmpEngine, "distant-agent-auth", "my-area", "noAuthNoPriv", 0)
config.addTargetAddr(
- snmpEngine, 'distant-agent',
- udp.domainName + (2,), ('104.236.166.95', 161),
- 'distant-agent-auth', retryCount=0
+ snmpEngine,
+ "distant-agent",
+ udp.domainName + (2,),
+ ("104.236.166.95", 161),
+ "distant-agent-auth",
+ retryCount=0,
)
# Default SNMP context
-config.addContext(snmpEngine, '')
+config.addContext(snmpEngine, "")
class CommandResponder(cmdrsp.CommandResponderBase):
@@ -96,31 +99,32 @@ class CommandResponder(cmdrsp.CommandResponderBase):
v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
- v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
+ v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(),
}
pduTypes = cmdGenMap.keys() # This app will handle these PDUs
# SNMP request relay
- def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
- PDU, acInfo):
+ def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo):
cbCtx = stateReference, PDU
contextEngineId = None # address authoritative SNMP Engine
try:
self.cmdGenMap[PDU.tagSet].sendPdu(
- snmpEngine, 'distant-agent',
- contextEngineId, contextName,
+ snmpEngine,
+ "distant-agent",
+ contextEngineId,
+ contextName,
PDU,
- self.handleResponsePdu, cbCtx
+ self.handleResponsePdu,
+ cbCtx,
)
except error.PySnmpError:
- self.handleResponsePdu(
- snmpEngine, stateReference, 'error', None, cbCtx
- )
+ self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx)
# SNMP response relay
# noinspection PyUnusedLocal
- def handleResponsePdu(self, snmpEngine, sendRequestHandle,
- errorIndication, PDU, cbCtx):
+ def handleResponsePdu(
+ self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx
+ ):
stateReference, reqPDU = cbCtx
if errorIndication:
diff --git a/pyproject.toml b/pyproject.toml
index 594717b..81517fb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,8 +1,8 @@
[tool.poetry]
name = "pysnmplib"
-version = "5.0.10"
+version = "5.0.21"
description = ""
-authors = ["rfaircloth-splunk <rfaircloth@splunk.com>"]
+authors = ["omrozowicz <omrozowicz@splunk.com>", "rfaircloth-splunk <rfaircloth@splunk.com>"]
license = "BSD-2-Clause"
repository = "https://github.com/pysnmp/pysnmp"
classifiers = [
diff --git a/pysnmp/__init__.py b/pysnmp/__init__.py
index f49ecb1..91434b2 100644
--- a/pysnmp/__init__.py
+++ b/pysnmp/__init__.py
@@ -1,5 +1,10 @@
# http://www.python.org/dev/peps/pep-0396/
-__version__ = '4.4.12'
+__version__ = '5.0.21'
+# another variable is required to prevent semantic release from updating version in more than one place
+main_version = __version__
# backward compatibility
-version = tuple(int(x) for x in __version__.split('.'))
+# for beta versions, integer casting throws an exception, so string part must be cut off
+if 'beta' in __version__:
+ main_version = __version__.split('-beta')[0]
+version = tuple(int(x) for x in main_version.split('.'))
majorVersionId = version[0]
diff --git a/pysnmp/carrier/asyncio/dispatch.py b/pysnmp/carrier/asyncio/dispatch.py
index f08ed0e..c9de556 100644
--- a/pysnmp/carrier/asyncio/dispatch.py
+++ b/pysnmp/carrier/asyncio/dispatch.py
@@ -50,10 +50,9 @@ class AsyncioDispatcher(AbstractTransportDispatcher):
self.loopingcall = None
self.loop = kwargs.pop('loop', asyncio.get_event_loop())
- @asyncio.coroutine
- def handle_timeout(self):
+ async def handle_timeout(self):
while True:
- yield asyncio.From(asyncio.sleep(self.getTimerResolution()))
+ await asyncio.sleep(self.getTimerResolution())
self.handleTimerTick(self.loop.time())
def runDispatcher(self, timeout=0.0):
@@ -64,7 +63,7 @@ class AsyncioDispatcher(AbstractTransportDispatcher):
raise
except Exception:
raise PySnmpError(';'.join(traceback.format_exception(*sys.exc_info())))
-
+
def registerTransport(self, tDomain, transport):
if self.loopingcall is None and self.getTimerResolution() > 0:
self.loopingcall = asyncio.ensure_future(self.handle_timeout())
diff --git a/pysnmp/debug.py b/pysnmp/debug.py
index c0f4d5d..705e0a3 100644
--- a/pysnmp/debug.py
+++ b/pysnmp/debug.py
@@ -123,4 +123,5 @@ def setLogger(l):
def hexdump(octets):
return ' '.join(
- ['{}{:.2X}'.format(n % 16 == 0 and ('\n%.5d: ' % n) or '', x) for n, x in zip(range(len(octets)), octs2ints(octets))])
+ ['{}{:02X}'.format(n % 16 == 0 and ('\n%.5d: ' % n) or '', x) for n, x in zip(range(len(octets)),
+ octs2ints(octets))])
diff --git a/pysnmp/hlapi/asyncio/cmdgen.py b/pysnmp/hlapi/asyncio/cmdgen.py
index 3b5942d..66945f7 100644
--- a/pysnmp/hlapi/asyncio/cmdgen.py
+++ b/pysnmp/hlapi/asyncio/cmdgen.py
@@ -52,15 +52,12 @@ lcd = CommandGeneratorLcdConfigurator()
isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1]
-@asyncio.coroutine
-def getCmd(snmpEngine, authData, transportTarget, contextData,
+
+async def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
- r"""Creates a generator to perform SNMP GET query.
+ r"""Perform SNMP GET.
- When iterator gets advanced by :py:mod:`asyncio` main loop,
- SNMP GET request is send (:RFC:`1905#section-4.2.1`).
- The iterator yields :py:class:`asyncio.Future` which gets done whenever
- response arrives or error occurs.
+ (:RFC:`1905#section-4.2.1`)
Parameters
----------
@@ -88,7 +85,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
- Yields
+ Returns
------
errorIndication : str
True value indicates SNMP engine error.
@@ -111,15 +108,15 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
>>> import asyncio
>>> from pysnmp.hlapi.asyncio import *
>>>
- >>> @asyncio.coroutine
- ... def run():
- ... errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
+ >>> async def run():
+ ... result_get = await getCmd(
... SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
... )
+ ... errorIndication, errorStatus, errorIndex, varBinds = result_get
... print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> asyncio.get_event_loop().run_until_complete(run())
@@ -148,7 +145,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
addrName, paramsName = lcd.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
- future = asyncio.Future()
+ future = asyncio.get_running_loop().create_future()
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
@@ -156,18 +153,14 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
- return future
+ return await future
-@asyncio.coroutine
-def setCmd(snmpEngine, authData, transportTarget, contextData,
+async def setCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
- r"""Creates a generator to perform SNMP SET query.
+ r"""Perform SNMP SET.
- When iterator gets advanced by :py:mod:`asyncio` main loop,
- SNMP SET request is send (:RFC:`1905#section-4.2.5`).
- The iterator yields :py:class:`asyncio.Future` which gets done whenever
- response arrives or error occurs.
+ (:RFC:`1905#section-4.2.5`)
Parameters
----------
@@ -195,7 +188,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
- Yields
+ Returns
------
errorIndication : str
True value indicates SNMP engine error.
@@ -218,9 +211,8 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
>>> import asyncio
>>> from pysnmp.hlapi.asyncio import *
>>>
- >>> @asyncio.coroutine
- ... def run():
- ... errorIndication, errorStatus, errorIndex, varBinds = yield from setCmd(
+ >>> async def run():
+ ... errorIndication, errorStatus, errorIndex, varBinds = await setCmd(
... SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
@@ -255,7 +247,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
addrName, paramsName = lcd.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
- future = asyncio.Future()
+ future = asyncio.get_running_loop().create_future()
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
@@ -263,18 +255,14 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
- return future
+ return await future
-@asyncio.coroutine
-def nextCmd(snmpEngine, authData, transportTarget, contextData,
+async def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
- r"""Creates a generator to perform SNMP GETNEXT query.
+ r"""Perform SNMP GETNEXT.
- When iterator gets advanced by :py:mod:`asyncio` main loop,
- SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`).
- The iterator yields :py:class:`asyncio.Future` which gets done whenever
- response arrives or error occurs.
+ (:RFC:`1905#section-4.2.2`)
Parameters
----------
@@ -302,7 +290,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
- Yields
+ Returns
------
errorIndication : str
True value indicates SNMP engine error.
@@ -329,9 +317,8 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
>>> import asyncio
>>> from pysnmp.hlapi.asyncio import *
>>>
- >>> @asyncio.coroutine
- ... def run():
- ... errorIndication, errorStatus, errorIndex, varBinds = yield from nextCmd(
+ >>> async def run():
+ ... errorIndication, errorStatus, errorIndex, varBinds = await nextCmd(
... SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
@@ -368,7 +355,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
addrName, paramsName = lcd.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
- future = asyncio.Future()
+ future = asyncio.get_running_loop().create_future()
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
@@ -376,18 +363,14 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
- return future
+ return await future
-@asyncio.coroutine
-def bulkCmd(snmpEngine, authData, transportTarget, contextData,
+async def bulkCmd(snmpEngine, authData, transportTarget, contextData,
nonRepeaters, maxRepetitions, *varBinds, **options):
- r"""Creates a generator to perform SNMP GETBULK query.
+ r"""Perform SNMP GETBULK.
- When iterator gets advanced by :py:mod:`asyncio` main loop,
- SNMP GETBULK request is send (:RFC:`1905#section-4.2.3`).
- The iterator yields :py:class:`asyncio.Future` which gets done whenever
- response arrives or error occurs.
+ (:RFC:`1905#section-4.2.3`)
Parameters
----------
@@ -425,8 +408,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
- Yields
- ------
+ Returns
+ -------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
@@ -470,9 +453,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
>>> import asyncio
>>> from pysnmp.hlapi.asyncio import *
>>>
- >>> @asyncio.coroutine
- ... def run():
- ... errorIndication, errorStatus, errorIndex, varBinds = yield from bulkCmd(
+ >>> async def run():
+ ... result_bulk = await bulkCmd(
... SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
@@ -480,9 +462,10 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
... 0, 2,
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... )
+ ... errorIndication, errorStatus, errorIndex, varBinds = result_bulk
... print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
- >>> asyncio.get_event_loop().run_until_complete(run())
+ >>> asyncio.run(run())
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))], [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.2.0')), ObjectIdentifier('1.3.6.1.4.1.424242.1.1'))]])
>>>
@@ -510,7 +493,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
addrName, paramsName = lcd.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
- future = asyncio.Future()
+ future = asyncio.get_running_loop().create_future()
cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
@@ -518,4 +501,4 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
- return future
+ return await future
diff --git a/pysnmp/hlapi/asyncio/ntforg.py b/pysnmp/hlapi/asyncio/ntforg.py
index 069e00e..1c5abf3 100644
--- a/pysnmp/hlapi/asyncio/ntforg.py
+++ b/pysnmp/hlapi/asyncio/ntforg.py
@@ -27,15 +27,9 @@ vbProcessor = NotificationOriginatorVarBinds()
lcd = NotificationOriginatorLcdConfigurator()
-@asyncio.coroutine
-def sendNotification(snmpEngine, authData, transportTarget, contextData,
+async def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, varBinds, **options):
- r"""Creates a generator to send SNMP notification.
-
- When iterator gets advanced by :py:mod:`asyncio` main loop,
- SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`).
- The iterator yields :py:class:`asyncio.Future` which gets done whenever
- response arrives or error occurs.
+ r"""Send SNMP notification.
Parameters
----------
@@ -71,7 +65,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
- Yields
+ Result
------
errorIndication : str
True value indicates SNMP engine error.
@@ -89,30 +83,23 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
Or its derivative indicating that an error occurred while
performing SNMP operation.
- Notes
- -----
- The `sendNotification` generator will be exhausted immidiately unless
- an instance of :py:class:`~pysnmp.smi.rfc1902.NotificationType` class
- or a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` `varBinds`
- are send back into running generator (supported since Python 2.6).
-
Examples
--------
>>> import asyncio
>>> from pysnmp.hlapi.asyncio import *
>>>
- >>> @asyncio.coroutine
- ... def run():
- ... errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification(
+ >>> async def run():
+ ... send_result = await sendNotification(
... SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
+ ... errorIndication, errorStatus, errorIndex, varBinds = send_result
... print(errorIndication, errorStatus, errorIndex, varBinds)
...
- >>> asyncio.get_event_loop().run_until_complete(run())
+ >>> asyncio.run(run())
(None, 0, 0, [])
>>>
@@ -139,7 +126,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
snmpEngine, authData, transportTarget, notifyType,
contextData.contextName)
- future = asyncio.Future()
+ future = asyncio.get_running_loop().create_future()
ntforg.NotificationOriginator().sendVarBinds(
snmpEngine,
@@ -160,4 +147,4 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
loop = asyncio.get_event_loop()
loop.call_soon(__trapFun, future)
- return future
+ return await future
diff --git a/pysnmp/hlapi/lcd.py b/pysnmp/hlapi/lcd.py
index 1899d67..6343aa1 100644
--- a/pysnmp/hlapi/lcd.py
+++ b/pysnmp/hlapi/lcd.py
@@ -36,7 +36,8 @@ class AbstractLcdConfigurator:
class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator):
cacheKeys = ['auth', 'parm', 'tran', 'addr']
- def configure(self, snmpEngine, authData, transportTarget, contextName, **options):
+ def configure(self, snmpEngine, authData, transportTarget, contextName=null,
+ **options):
cache = self._getCache(snmpEngine)
if isinstance(authData, CommunityData):
if authData.communityIndex not in cache['auth']:
diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py
index 3454de2..ba78ce2 100644
--- a/pysnmp/proto/secmod/rfc3414/service.py
+++ b/pysnmp/proto/secmod/rfc3414/service.py
@@ -13,7 +13,7 @@ from pysnmp.proto.secmod.rfc3826.priv import aes
from pysnmp.proto.secmod.rfc7860.auth import hmacsha2
from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256
from pysnmp.smi.error import NoSuchInstanceError
-from pysnmp.proto import api, rfc1155, errind, error
+from pysnmp.proto import api, rfc1155, rfc3411, errind, error
from pysnmp import debug
from pyasn1.type import univ, namedtype, constraint
from pyasn1.codec.ber import encoder, decoder, eoo
@@ -446,34 +446,40 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
)
# 3.1.6a
- if securityStateReference is None and securityLevel in (2, 3):
- if securityEngineID in self.__timeline:
- (snmpEngineBoots, snmpEngineTime, latestReceivedEngineTime,
+ snmpEngineBoots = snmpEngineTime = 0
+
+ if securityLevel in (2, 3):
+ pdu = scopedPDU.getComponentByPosition(2).getComponent()
+
+ # 3.1.6.b
+ if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
+ (snmpEngineBoots,
+ snmpEngineTime) = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime')
+
+ snmpEngineBoots = snmpEngineBoots.syntax
+ snmpEngineTime = snmpEngineTime.syntax.clone()
+
+ debug.logger & debug.flagSM and debug.logger(
+ '__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD')
+
+ # 3.1.6a
+ elif securityEngineID in self.__timeline:
+ (snmpEngineBoots,
+ snmpEngineTime,
+ latestReceivedEngineTime,
latestUpdateTimestamp) = self.__timeline[securityEngineID]
+
debug.logger & debug.flagSM and debug.logger(
'__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline')
+
+ # 3.1.6.c
else:
- # 2.3 XXX is this correct?
- snmpEngineBoots = snmpEngineTime = 0
debug.logger & debug.flagSM and debug.logger(
- f'__generateRequestOrResponseMsg: no timeline for securityEngineID {securityEngineID!r}')
- # 3.1.6.b
- elif securityStateReference is not None: # XXX Report?
- (snmpEngineBoots,
- snmpEngineTime) = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime')
- snmpEngineBoots = snmpEngineBoots.syntax
- snmpEngineTime = snmpEngineTime.syntax.clone()
- debug.logger & debug.flagSM and debug.logger(
- '__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD')
- # 3.1.6.c
- else:
- snmpEngineBoots = snmpEngineTime = 0
- debug.logger & debug.flagSM and debug.logger(
- '__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime')
+ '__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime')
- debug.logger & debug.flagSM and debug.logger(
- '__generateRequestOrResponseMsg: use snmpEngineBoots {} snmpEngineTime {} for securityEngineID {!r}'.format(
- snmpEngineBoots, snmpEngineTime, securityEngineID))
+ debug.logger & debug.flagSM and debug.logger(
+ '__generateRequestOrResponseMsg: use snmpEngineBoots {} snmpEngineTime {} for securityEngineID {!r}'.format(
+ snmpEngineBoots, snmpEngineTime, securityEngineID))
# 3.1.4a
if securityLevel == 3:
diff --git a/pysnmp/smi/indices.py b/pysnmp/smi/indices.py
index f1d2ce1..092318a 100644
--- a/pysnmp/smi/indices.py
+++ b/pysnmp/smi/indices.py
@@ -20,16 +20,16 @@ class OrderedDict(dict):
self.update(**kwargs)
def __setitem__(self, key, value):
- super().__setitem__(key, value)
- if key not in self.__keys:
+ if key not in self:
self.__keys.append(key)
self.__dirty = True
+ super().__setitem__(key, value)
def __delitem__(self, key):
- super().__delitem__(key)
- if key in self.__keys:
+ if key in self:
self.__keys.remove(key)
self.__dirty = True
+ super().__delitem__(key)
def clear(self):
super().clear()
diff --git a/pysnmp/smi/rfc1902.py b/pysnmp/smi/rfc1902.py
index 87a9d4e..3274c23 100644
--- a/pysnmp/smi/rfc1902.py
+++ b/pysnmp/smi/rfc1902.py
@@ -303,7 +303,7 @@ class ObjectIdentity:
# this would eventually be called by an entity which posses a
# reference to MibViewController
- def resolveWithMib(self, mibViewController):
+ def resolveWithMib(self, mibViewController, ignoreErrors=True):
"""Perform MIB variable ID conversion.
Parameters
@@ -383,7 +383,7 @@ class ObjectIdentity:
self.__indices = ()
if isinstance(self.__args[0], ObjectIdentity):
- self.__args[0].resolveWithMib(mibViewController)
+ self.__args[0].resolveWithMib(mibViewController, ignoreErrors)
if len(self.__args) == 1: # OID or label or MIB module
debug.logger & debug.flagMIB and debug.logger('resolving %s as OID or label' % self.__args)
@@ -448,9 +448,6 @@ class ObjectIdentity:
rowModName, rowSymName
)
self.__indices = rowNode.getIndicesFromInstId(suffix)
- elif isinstance(mibNode, MibScalar): # scalar
- if suffix:
- self.__indices = (rfc1902.ObjectName(suffix),)
else:
if suffix:
self.__indices = (rfc1902.ObjectName(suffix),)