From 85d6c87cb1ab06c4dd6f47d354dbd72e78b96c0e Mon Sep 17 00:00:00 2001 From: Lex Li <support@lextm.com> Date: Sat, 12 Oct 2024 04:07:57 -0400 Subject: [PATCH] Applied more PEP 8 renaming. --- .flake8 | 2 +- docs/source/docs/pysnmp-hlapi-tutorial.rst | 2 +- docs/source/faq/getting-peer-information.rst | 26 +- .../source/faq/how-to-implement-agent-mib.rst | 52 ++- docs/source/faq/oids-not-increasing.rst | 2 +- .../asyncio/agent/ntforg/default-v1-trap.py | 2 +- .../asyncio/manager/cmdgen/getbulk-to-eom.py | 2 +- .../v1arch/asyncio/manager/cmdgen/v1-get.py | 2 +- .../asyncio/agent/ntforg/default-v1-trap.py | 2 +- .../agent/ntforg/multiple-informs-at-once.py | 2 +- .../agent/ntforg/multiple-traps-at-once.py | 2 +- .../running-multiple-snmp-engines-at-once.py | 14 +- .../v3arch/asyncio/agent/ntforg/send-trap.py | 4 +- .../v3arch/asyncio/agent/ntforg/v3-inform.py | 2 +- ...tiple-agents-at-once-over-ipv4-and-ipv6.py | 2 +- .../asyncio/manager/cmdgen/pull-whole-mib.py | 2 +- ...ultiple-snmp-engines-over-ipv4-and-ipv6.py | 14 +- .../v3arch/asyncio/manager/cmdgen/v1-get.py | 2 +- examples/smi/agent/custom-managed-object.py | 2 +- ...g-scalar-mib-objects-over-ipv4-and-ipv6.py | 16 +- .../ntforg/send-inform-over-ipv4-and-ipv6.py | 10 +- .../ntforg/send-trap-over-ipv4-and-ipv6.py | 10 +- .../cmdgen/broadcast-agent-discovery.py | 10 +- .../manager/cmdgen/fetch-scalar-value.py | 10 +- .../manager/cmdgen/getbulk-pull-whole-mib.py | 10 +- .../manager/cmdgen/getnext-pull-whole-mib.py | 10 +- .../v1arch/asyncio/manager/cmdgen/v2c-set.py | 10 +- .../listen-on-ipv4-and-ipv6-interfaces.py | 16 +- .../agent/cmdrsp/alternative-mib-tree.py | 14 +- .../agent/cmdrsp/custom-mib-controller.py | 16 +- .../agent/cmdrsp/custom-snmp-engine-id.py | 14 +- .../cmdrsp/detailed-vacm-configuration.py | 24 +- .../cmdrsp/implementing-scalar-mib-objects.py | 16 +- .../agent/cmdrsp/implementing-snmp-table.py | 18 +- .../agent/cmdrsp/listen-on-custom-socket.py | 14 +- .../listen-on-ipv4-and-ipv6-interfaces.py | 18 +- .../cmdrsp/listen-on-multiple-interfaces.py | 18 +- .../agent/cmdrsp/multiple-snmp-communities.py | 18 +- .../agent/cmdrsp/multiple-snmp-contexts.py | 14 +- .../agent/cmdrsp/multiple-snmp-engines.py | 20 +- .../agent/cmdrsp/multiple-usm-users.py | 22 +- .../cmdrsp/observe-request-processing.py | 14 +- ...ultiple-different-notifications-at-once.py | 26 +- .../asyncio/agent/ntforg/send-custom-pdu.py | 10 +- .../send-inform-to-multiple-managers.py | 22 +- .../send-notification-over-ipv4-and-ipv6.py | 24 +- .../send-packet-from-specific-address.py | 18 +- .../ntforg/send-trap-to-multiple-managers.py | 22 +- .../asyncio/agent/ntforg/usm-md5-none.py | 18 +- .../v3arch/asyncio/agent/ntforg/v1-trap.py | 18 +- .../v3arch/asyncio/agent/ntforg/v2c-inform.py | 18 +- .../v2c-trap-with-notification-objects.py | 20 +- .../v3arch/asyncio/agent/ntforg/v2c-trap.py | 18 +- .../v3arch/asyncio/agent/ntforg/v3-trap.py | 18 +- .../custom-contextengineid-and-contextname.py | 12 +- .../cmdgen/custom-timeout-and-retries.py | 12 +- .../cmdgen/fetch-variables-over-ipv6.py | 12 +- ...etbulk-fetch-scalar-and-table-variables.py | 12 +- .../cmdgen/getbulk-multiple-oids-to-eom.py | 12 +- ...next-multiple-oids-and-resolve-with-mib.py | 16 +- .../cmdgen/getnext-multiple-oids-to-eom.py | 12 +- .../cmdgen/observe-request-processing.py | 12 +- .../asyncio/manager/cmdgen/pull-subtree.py | 12 +- .../send-packets-from-specific-interface.py | 12 +- .../cmdgen/set-multiple-scalar-values.py | 12 +- .../asyncio/manager/cmdgen/usm-sha-aes128.py | 12 +- .../asyncio/manager/cmdgen/usm-sha-none.py | 12 +- .../v3arch/asyncio/manager/cmdgen/v1-get.py | 12 +- .../v3arch/asyncio/manager/cmdgen/v2c-set.py | 10 +- .../ntfrcv/determine-peer-network-address.py | 12 +- .../ntfrcv/multiple-network-interfaces.py | 16 +- ...e-network-transports-incl-ipv4-and-ipv6.py | 16 +- .../manager/ntfrcv/multiple-usm-users.py | 18 +- ...e-request-processing-over-ipv4-and-ipv6.py | 16 +- .../manager/ntfrcv/regexp-community-name.py | 12 +- .../proxy/command/ipv6-to-ipv4-conversion.py | 22 +- .../proxy/command/v2c-to-v1-conversion.py | 24 +- .../proxy/command/v2c-to-v3-conversion.py | 26 +- .../proxy/command/v3-to-v2c-conversion.py | 26 +- poetry.lock | 16 +- pyproject.toml | 1 + pysnmp/carrier/asyncio/dgram/base.py | 16 +- pysnmp/carrier/asyncio/dispatch.py | 28 +- pysnmp/carrier/base.py | 90 ++-- pysnmp/debug.py | 2 +- pysnmp/entity/config.py | 412 +++++++++--------- pysnmp/entity/engine.py | 92 ++-- pysnmp/entity/observer.py | 10 +- pysnmp/entity/rfc3413/cmdgen.py | 40 +- pysnmp/entity/rfc3413/cmdrsp.py | 40 +- pysnmp/entity/rfc3413/config.py | 36 +- pysnmp/entity/rfc3413/context.py | 6 +- pysnmp/entity/rfc3413/ntforg.py | 22 +- pysnmp/entity/rfc3413/ntfrcv.py | 19 +- pysnmp/hlapi/transport.py | 30 +- pysnmp/hlapi/v1arch/asyncio/slim.py | 2 +- pysnmp/hlapi/v1arch/asyncio/transport.py | 4 +- pysnmp/hlapi/v1arch/dispatch.py | 50 ++- pysnmp/hlapi/v3arch/asyncio/lcd.py | 65 +-- pysnmp/hlapi/v3arch/asyncio/ntforg.py | 2 +- pysnmp/hlapi/v3arch/asyncio/transport.py | 4 +- pysnmp/proto/acmod/rfc3415.py | 22 +- pysnmp/proto/acmod/void.py | 8 +- pysnmp/proto/api/__init__.py | 2 +- pysnmp/proto/api/verdec.py | 2 +- pysnmp/proto/mpmod/base.py | 13 +- pysnmp/proto/mpmod/rfc2576.py | 26 +- pysnmp/proto/mpmod/rfc3412.py | 50 +-- pysnmp/proto/rfc3412.py | 66 +-- pysnmp/proto/secmod/base.py | 15 +- pysnmp/proto/secmod/eso/priv/aesbase.py | 4 +- pysnmp/proto/secmod/eso/priv/des3.py | 8 +- pysnmp/proto/secmod/rfc2576.py | 61 ++- pysnmp/proto/secmod/rfc3414/auth/base.py | 10 +- pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py | 10 +- pysnmp/proto/secmod/rfc3414/auth/hmacsha.py | 10 +- pysnmp/proto/secmod/rfc3414/auth/noauth.py | 8 +- pysnmp/proto/secmod/rfc3414/priv/base.py | 8 +- pysnmp/proto/secmod/rfc3414/priv/des.py | 8 +- pysnmp/proto/secmod/rfc3414/priv/nopriv.py | 8 +- pysnmp/proto/secmod/rfc3414/service.py | 119 ++--- pysnmp/proto/secmod/rfc3826/priv/aes.py | 8 +- pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py | 10 +- tests/agent_context.py | 44 +- .../manager/cmdgen/test_v1arch_v1_get.py | 10 +- .../manager/cmdgen/test_v1arch_v1_next.py | 2 +- .../manager/cmdgen/test_v1arch_v1_set.py | 4 +- .../manager/cmdgen/test_v1arch_v1_walk.py | 4 +- .../manager/cmdgen/test_v1arch_v2_walk.py | 4 +- .../manager/cmdgen/test_v1arch_v2c_bulk.py | 2 +- .../cmdgen/test_v1arch_v2c_bulkwalk.py | 18 +- .../manager/cmdgen/test_v1arch_v2c_get.py | 6 +- .../manager/cmdgen/test_v1arch_v2c_next.py | 2 +- .../manager/cmdgen/test_v1arch_v2c_set.py | 2 +- .../agent/ntforg/test_default-v1-trap.py | 8 +- .../asyncio/agent/ntforg/test_v3-inform.py | 2 +- .../asyncio/agent/ntforg/test_v3-trap.py | 6 +- .../test_custom_asn1_mib_search_path.py | 2 +- .../manager/cmdgen/test_lcd_configurator.py | 22 +- .../asyncio/manager/cmdgen/test_v1_get.py | 10 +- .../asyncio/manager/cmdgen/test_v1_next.py | 2 +- .../asyncio/manager/cmdgen/test_v1_set.py | 2 +- .../asyncio/manager/cmdgen/test_v1_walk.py | 6 +- .../asyncio/manager/cmdgen/test_v2_walk.py | 4 +- .../asyncio/manager/cmdgen/test_v2c_bulk.py | 4 +- .../manager/cmdgen/test_v2c_bulkwalk.py | 18 +- .../asyncio/manager/cmdgen/test_v2c_get.py | 6 +- .../asyncio/manager/cmdgen/test_v2c_next.py | 2 +- .../asyncio/manager/cmdgen/test_v2c_set.py | 2 +- .../manager/cmdgen/test_v3_usm_none_none.py | 2 +- .../manager/cmdgen/test_v3_usm_sha_aes128.py | 8 +- .../manager/cmdgen/test_v3_usm_sha_aes256.py | 6 +- .../manager/cmdgen/test_v3_usm_sha_none.py | 6 +- tests/manager_context.py | 20 +- 154 files changed, 1432 insertions(+), 1349 deletions(-) diff --git a/.flake8 b/.flake8 index b6dd74d50..f895f269f 100644 --- a/.flake8 +++ b/.flake8 @@ -1,4 +1,4 @@ [flake8] import-order-style = smarkets exclude = .git,__pycache__,docs/source/conf.py,old,build,dist,pysnmp/smi/mibs -ignore = D100, D401, E203, E722, E501, W503, F401, F403, RST210, RST213, RST304 +ignore = D100, D401, E203, E722, E501, W503, F401, F403, N803, N806, RST210, RST213, RST304 diff --git a/docs/source/docs/pysnmp-hlapi-tutorial.rst b/docs/source/docs/pysnmp-hlapi-tutorial.rst index ac5efb68a..fb102c880 100644 --- a/docs/source/docs/pysnmp-hlapi-tutorial.rst +++ b/docs/source/docs/pysnmp-hlapi-tutorial.rst @@ -33,7 +33,7 @@ operations. .. warning:: ``SnmpEngine`` object allocates many resources under the hood, so make - sure to call its :py:meth:`~pysnmp.hlapi.v3arch.asyncio.SnmpEngine.closeDispatcher` + sure to call its :py:meth:`~pysnmp.hlapi.v3arch.asyncio.SnmpEngine.close_dispatcher` method when you are done with it. Making SNMP Query diff --git a/docs/source/faq/getting-peer-information.rst b/docs/source/faq/getting-peer-information.rst index cf7880284..3b637a02b 100644 --- a/docs/source/faq/getting-peer-information.rst +++ b/docs/source/faq/getting-peer-information.rst @@ -2,23 +2,23 @@ Getting peer address information -------------------------------- -Q. How do I find out peer transport address or security information within +Q. How do I find out peer transport address or security information within my receiving app (CommandResponder or Notification Receiver)? -A. SNMP architecture forces you to distinguish communicating entities only - on the basis of their community names (SNMPv1/v2c) or - ContextEngineId/ContextName pair (SNMPv3). - - In other words, if one SNMP Manager should anyhow differ from another, - then they should use distinct community names or SNMP contexts. +A. SNMP architecture forces you to distinguish communicating entities only + on the basis of their community names (SNMPv1/v2c) or + ContextEngineId/ContextName pair (SNMPv3). + + In other words, if one SNMP Manager should anyhow differ from another, + then they should use distinct community names or SNMP contexts. Transport information should never be used for the identification purposes, - as in some cases it proves to be unreliable (cases include NAT device or + as in some cases it proves to be unreliable (cases include NAT device or a proxy in the middle, not to mention address spoofing). - As practice reveals, even perfect design does not always cope well with - the imperfect world. So we had to pinch a logic hole from the scope of an - SNMP app down to transport layer. Now with the - getTransportInfo(stateReference) method call you could get peer transport + As practice reveals, even perfect design does not always cope well with + the imperfect world. So we had to pinch a logic hole from the scope of an + SNMP app down to transport layer. Now with the + getTransportInfo(stateReference) method call you could get peer transport information upon receiving its SNMP message. .. code-block:: python @@ -29,4 +29,4 @@ A. SNMP architecture forces you to distinguish communicating entities only contextEngineId, contextName, varBinds, cbCtx): - transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) + transportDomain, transportAddress = snmpEngine.message_dispatcher.getTransportInfo(stateReference) diff --git a/docs/source/faq/how-to-implement-agent-mib.rst b/docs/source/faq/how-to-implement-agent-mib.rst index d667fb074..fcf04fcfd 100644 --- a/docs/source/faq/how-to-implement-agent-mib.rst +++ b/docs/source/faq/how-to-implement-agent-mib.rst @@ -4,7 +4,7 @@ How to implement MIB at the Agent Q. How to instantiate static MIB table at my SNMP Agent? -A. You need to create MibScalarInstance class instances and register +A. You need to create MibScalarInstance class instances and register them with your Agent's SNMP engine (mibBuilder, more specifically). Here's an example code for a IP-MIB table: @@ -19,31 +19,29 @@ A. You need to create MibScalarInstance class instances and register ipAddressIfIndex, ipAddressType, ipAddressPrefix, - ipAddressOrigin, - ipAddressStatus, - ipAddressCreated, - ipAddressLastChanged, - ipAddressRowStatus, - ipAddressStorageType ) = snmpEngine.msgAndPduDsp.mibInstrumController - .mibBuilder.importSymbols( + ipAddressOrigin, + ipAddressStatus, + ipAddressCreated, + ipAddressLastChanged, + ipAddressRowStatus, + ipAddressStorageType ) = snmpEngine.get_mib_builder().importSymbols( 'IP-MIB', 'ipAddressAddrType', - 'ipAddressAddr', - 'ipAddressIfIndex', - 'ipAddressType', + 'ipAddressAddr', + 'ipAddressIfIndex', + 'ipAddressType', 'ipAddressPrefix', 'ipAddressOrigin', 'ipAddressStatus', 'ipAddressCreated', - 'ipAddressLastChanged', - 'ipAddressRowStatus', + 'ipAddressLastChanged', + 'ipAddressRowStatus', 'ipAddressStorageType' ) # Import MibScalarInstance - MibScalarInstance, = snmpEngine.msgAndPduDsp.mibInstrumController. - mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') + MibScalarInstance, = snmpEngine.get_mib_builder().importSymbols('SNMPv2-SMI', 'MibScalarInstance') # Create table columns instances @@ -52,11 +50,11 @@ A. You need to create MibScalarInstance class instances and register ipAddressAddrType.syntax.clone(1) ) _ipAddressAddr = MibScalarInstance( - ipAddressAddr.name, (1, 4, 1, 2, 3, 4), + ipAddressAddr.name, (1, 4, 1, 2, 3, 4), ipAddressAddr.syntax.clone('1.2.3.4') ) _ipAddressIfIndex = MibScalarInstance( - ipAddressIfIndex.name, (1, 4, 1, 2, 3, 4), + ipAddressIfIndex.name, (1, 4, 1, 2, 3, 4), ipAddressIfIndex.syntax.clone(1) ) _ipAddressType = MibScalarInstance( @@ -64,7 +62,7 @@ A. You need to create MibScalarInstance class instances and register ipAddressType.syntax.clone(1) ) _ipAddressPrefix = MibScalarInstance( - ipAddressPrefix.name, (1, 4, 1, 2, 3, 4), + ipAddressPrefix.name, (1, 4, 1, 2, 3, 4), ipAddressPrefix.syntax.clone((0,0)) ) _ipAddressOrigin = MibScalarInstance( @@ -76,15 +74,15 @@ A. You need to create MibScalarInstance class instances and register ipAddressStatus.syntax.clone(1) ) _ipAddressCreated = MibScalarInstance( - ipAddressCreated.name, (1, 4, 1, 2, 3, 4), + ipAddressCreated.name, (1, 4, 1, 2, 3, 4), ipAddressCreated.syntax.clone(800) ) _ipAddressLastChanged = MibScalarInstance( - ipAddressLastChanged.name, (1, 4, 1, 2, 3, 4), + ipAddressLastChanged.name, (1, 4, 1, 2, 3, 4), ipAddressLastChanged.syntax.clone(600) ) _ipAddressRowStatus = MibScalarInstance( - ipAddressRowStatus.name, (1, 4, 1, 2, 3, 4), + ipAddressRowStatus.name, (1, 4, 1, 2, 3, 4), ipAddressRowStatus.syntax.clone(1) ) _ipAddressStorageType = MibScalarInstance( @@ -93,7 +91,7 @@ A. You need to create MibScalarInstance class instances and register ) # add anonymous column instances - snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols( + snmpEngine.get_mib_builder().exportSymbols( '_IP-MIB', _ipAddressAddrType, _ipAddressAddr, @@ -110,11 +108,11 @@ A. You need to create MibScalarInstance class instances and register # Command responder code would follow... -Keep in mind that the values of this table row will not change by -themselves. They basically hold a snapshot of a data set so your -application may have to update them somehow. For example, an app could -periodically lookup particular MibScalarInstance by OID at mibBuilder and +Keep in mind that the values of this table row will not change by +themselves. They basically hold a snapshot of a data set so your +application may have to update them somehow. For example, an app could +periodically lookup particular MibScalarInstance by OID at mibBuilder and update its "syntax" attribute with a new value. -There are other ways for building MIB tables that represent dynamic +There are other ways for building MIB tables that represent dynamic Managed Objects. diff --git a/docs/source/faq/oids-not-increasing.rst b/docs/source/faq/oids-not-increasing.rst index d79b74736..ce9360f3a 100644 --- a/docs/source/faq/oids-not-increasing.rst +++ b/docs/source/faq/oids-not-increasing.rst @@ -46,4 +46,4 @@ A. The Agent you are talking to seems to be broken. The for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind]) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/examples/hlapi/v1arch/asyncio/agent/ntforg/default-v1-trap.py b/examples/hlapi/v1arch/asyncio/agent/ntforg/default-v1-trap.py index c76dd3038..4f0bd48f9 100644 --- a/examples/hlapi/v1arch/asyncio/agent/ntforg/default-v1-trap.py +++ b/examples/hlapi/v1arch/asyncio/agent/ntforg/default-v1-trap.py @@ -45,7 +45,7 @@ async def run(): if errorIndication: print(errorIndication) - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v1arch/asyncio/manager/cmdgen/getbulk-to-eom.py b/examples/hlapi/v1arch/asyncio/manager/cmdgen/getbulk-to-eom.py index 00a35be29..d8c3481d2 100644 --- a/examples/hlapi/v1arch/asyncio/manager/cmdgen/getbulk-to-eom.py +++ b/examples/hlapi/v1arch/asyncio/manager/cmdgen/getbulk-to-eom.py @@ -55,7 +55,7 @@ async def run(varBinds): if isEndOfMib(varBinds): break - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() asyncio.run(run([ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr"))])) diff --git a/examples/hlapi/v1arch/asyncio/manager/cmdgen/v1-get.py b/examples/hlapi/v1arch/asyncio/manager/cmdgen/v1-get.py index 3b1715997..1320ab84d 100644 --- a/examples/hlapi/v1arch/asyncio/manager/cmdgen/v1-get.py +++ b/examples/hlapi/v1arch/asyncio/manager/cmdgen/v1-get.py @@ -45,7 +45,7 @@ async def run(): for varBind in varBinds: print(" = ".join([x.prettyPrint() for x in varBind])) - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/default-v1-trap.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/default-v1-trap.py index b7b856de4..af2127c68 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/default-v1-trap.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/default-v1-trap.py @@ -43,7 +43,7 @@ async def run(): if errorIndication: print(errorIndication) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-informs-at-once.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-informs-at-once.py index 52afcb9fa..ba43683c9 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-informs-at-once.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-informs-at-once.py @@ -71,7 +71,7 @@ async def run(): for name, val in varBindTable: print(f"{name.prettyPrint()} = {val.prettyPrint()}") - snmpEngine.transportDispatcher.runDispatcher() + snmpEngine.transport_dispatcher.run_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-traps-at-once.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-traps-at-once.py index 023cd2763..513b78910 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-traps-at-once.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/multiple-traps-at-once.py @@ -54,7 +54,7 @@ async def run(): ), ) - snmpEngine.transportDispatcher.runDispatcher() + snmpEngine.transport_dispatcher.run_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/running-multiple-snmp-engines-at-once.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/running-multiple-snmp-engines-at-once.py index a1e19cb0f..a8b071fc7 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/running-multiple-snmp-engines-at-once.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/running-multiple-snmp-engines-at-once.py @@ -56,18 +56,22 @@ async def run(): transportDispatcher = AsyncioDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain - transportDispatcher.registerRoutingCbFun(lambda td, ta, d: ta[1] % 3 and "A" or "B") + transportDispatcher.register_routing_callback( + lambda td, ta, d: ta[1] % 3 and "A" or "B" + ) snmpEngineA = SnmpEngine() - snmpEngineA.registerTransportDispatcher(transportDispatcher, "A") + snmpEngineA.register_transport_dispatcher(transportDispatcher, "A") snmpEngineB = SnmpEngine() - snmpEngineB.registerTransportDispatcher(transportDispatcher, "B") + snmpEngineB.register_transport_dispatcher(transportDispatcher, "B") for authData, transportTarget, contextData in TARGETS: # Pick one of the two SNMP engines snmpEngine = ( - transportTarget.getTransportInfo()[1][1] % 3 and snmpEngineA or snmpEngineB + transportTarget.get_transport_info()[1][1] % 3 + and snmpEngineA + or snmpEngineB ) errorIndication, errorStatus, errorIndex, varBinds = await sendNotification( @@ -104,7 +108,7 @@ async def run(): for name, val in varBinds: print(f"{name.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.runDispatcher() + transportDispatcher.run_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/send-trap.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/send-trap.py index 037956a67..27cc81998 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/send-trap.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/send-trap.py @@ -5,7 +5,7 @@ async def run(): snmpEngine = SnmpEngine() # Example of how you might update sysUpTime - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (sysUpTime,) = mibBuilder.importSymbols("__SNMPv2-MIB", "sysUpTime") sysUpTime.syntax = TimeTicks(12345) # Set uptime to 12345 @@ -28,7 +28,7 @@ async def run(): if errorIndication: print(errorIndication) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/agent/ntforg/v3-inform.py b/examples/hlapi/v3arch/asyncio/agent/ntforg/v3-inform.py index affcaa05f..6f749f49c 100644 --- a/examples/hlapi/v3arch/asyncio/agent/ntforg/v3-inform.py +++ b/examples/hlapi/v3arch/asyncio/agent/ntforg/v3-inform.py @@ -44,7 +44,7 @@ async def run(): for varBind in varBinds: print(" = ".join([x.prettyPrint() for x in varBind])) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py b/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py index e3ed26130..4a78b0bcd 100644 --- a/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py +++ b/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py @@ -76,7 +76,7 @@ async def run(): for varBind in varBindTable: print(" = ".join([x.prettyPrint() for x in varBind])) - snmpEngine.transportDispatcher.runDispatcher() + snmpEngine.transport_dispatcher.run_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-whole-mib.py b/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-whole-mib.py index 7b98c8be0..1eb87920e 100644 --- a/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-whole-mib.py +++ b/examples/hlapi/v3arch/asyncio/manager/cmdgen/pull-whole-mib.py @@ -47,7 +47,7 @@ async def run(): for varBind in varBindTable: print(" = ".join([x.prettyPrint() for x in varBind])) - snmpEngine.transportDispatcher.runDispatcher() + snmpEngine.transport_dispatcher.run_dispatcher() asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py b/examples/hlapi/v3arch/asyncio/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py index 7255a4164..d25ac1c01 100644 --- a/examples/hlapi/v3arch/asyncio/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py +++ b/examples/hlapi/v3arch/asyncio/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py @@ -73,21 +73,25 @@ async def run(): transportDispatcher = AsyncioDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain - transportDispatcher.registerRoutingCbFun(lambda td, ta, d: ta[1] % 3 and "A" or "B") + transportDispatcher.register_routing_callback( + lambda td, ta, d: ta[1] % 3 and "A" or "B" + ) snmpEngineA = SnmpEngine() snmpEngineIDA = snmpEngineA.snmpEngineID print("snmpEngineA ID: %s" % snmpEngineIDA.prettyPrint()) - snmpEngineA.registerTransportDispatcher(transportDispatcher, "A") + snmpEngineA.register_transport_dispatcher(transportDispatcher, "A") snmpEngineB = SnmpEngine() snmpEngineIDB = snmpEngineB.snmpEngineID print("snmpEngineB ID: %s" % snmpEngineIDB.prettyPrint()) - snmpEngineB.registerTransportDispatcher(transportDispatcher, "B") + snmpEngineB.register_transport_dispatcher(transportDispatcher, "B") for authData, transportTarget, varBinds in TARGETS: snmpEngine = ( - transportTarget.getTransportInfo()[1][1] % 3 and snmpEngineA or snmpEngineB + transportTarget.get_transport_info()[1][1] % 3 + and snmpEngineA + or snmpEngineB ) (errorIndication, errorStatus, errorIndex, varBindTable) = await getCmd( @@ -117,7 +121,7 @@ async def run(): for varBind in varBindTable: print(" = ".join([x.prettyPrint() for x in varBind])) - transportDispatcher.runDispatcher(5) + transportDispatcher.run_dispatcher(5) asyncio.run(run()) diff --git a/examples/hlapi/v3arch/asyncio/manager/cmdgen/v1-get.py b/examples/hlapi/v3arch/asyncio/manager/cmdgen/v1-get.py index 85e20c1d0..c4498596a 100644 --- a/examples/hlapi/v3arch/asyncio/manager/cmdgen/v1-get.py +++ b/examples/hlapi/v3arch/asyncio/manager/cmdgen/v1-get.py @@ -46,7 +46,7 @@ async def run(): for varBind in varBinds: print(" = ".join([x.prettyPrint() for x in varBind])) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() asyncio.run(run()) diff --git a/examples/smi/agent/custom-managed-object.py b/examples/smi/agent/custom-managed-object.py index 516a80c74..e85e12688 100644 --- a/examples/smi/agent/custom-managed-object.py +++ b/examples/smi/agent/custom-managed-object.py @@ -53,7 +53,7 @@ def readGet(self, varBind, **context): varBinds = [((), None)] while True: - varBinds = mibInstrum.readNextVars(*varBinds) + varBinds = mibInstrum.read_next_variables(*varBinds) oid, val = varBinds[0] if exval.endOfMib.isSameTypeWith(val): break diff --git a/examples/v1arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py b/examples/v1arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py index 802e709bb..33e82d9fe 100644 --- a/examples/v1arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py +++ b/examples/v1arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py @@ -145,28 +145,28 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbFun) +transportDispatcher.register_recv_callback(cbFun) # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openServerMode(("localhost", 161)) +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_server_mode(("localhost", 161)) ) # UDP/IPv6 -transportDispatcher.registerTransport( - udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().openServerMode(("::1", 161)) +transportDispatcher.register_transport( + udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().open_server_mode(("::1", 161)) ) -transportDispatcher.jobStarted(1) +transportDispatcher.job_started(1) try: print("This program needs to run as root/administrator to monitor port 161.") print("Started. Press Ctrl-C to stop") # Dispatcher will never finish as job#1 never reaches zero - transportDispatcher.runDispatcher() + transportDispatcher.run_dispatcher() except KeyboardInterrupt: print("Shutting down...") finally: - transportDispatcher.closeDispatcher() + transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/agent/ntforg/send-inform-over-ipv4-and-ipv6.py b/examples/v1arch/asyncio/agent/ntforg/send-inform-over-ipv4-and-ipv6.py index 2c724597b..bc77833d1 100644 --- a/examples/v1arch/asyncio/agent/ntforg/send-inform-over-ipv4-and-ipv6.py +++ b/examples/v1arch/asyncio/agent/ntforg/send-inform-over-ipv4-and-ipv6.py @@ -56,13 +56,13 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(trapMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 162) ) transportDispatcher.jobStarted(1) @@ -79,4 +79,4 @@ def cbRecvFun( # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/agent/ntforg/send-trap-over-ipv4-and-ipv6.py b/examples/v1arch/asyncio/agent/ntforg/send-trap-over-ipv4-and-ipv6.py index 48732785e..7de5180b0 100644 --- a/examples/v1arch/asyncio/agent/ntforg/send-trap-over-ipv4-and-ipv6.py +++ b/examples/v1arch/asyncio/agent/ntforg/send-trap-over-ipv4-and-ipv6.py @@ -49,20 +49,20 @@ transportDispatcher = AsyncioDispatcher() # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(trapMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 162) ) # UDP/IPv6 transportDispatcher.registerTransport( - udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().openClientMode() + udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().open_client_mode() ) transportDispatcher.sendMessage(encoder.encode(trapMsg), udp6.DOMAIN_NAME, ("::1", 162)) # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/cmdgen/broadcast-agent-discovery.py b/examples/v1arch/asyncio/manager/cmdgen/broadcast-agent-discovery.py index 7658bd58b..1cedfb0a4 100644 --- a/examples/v1arch/asyncio/manager/cmdgen/broadcast-agent-discovery.py +++ b/examples/v1arch/asyncio/manager/cmdgen/broadcast-agent-discovery.py @@ -69,14 +69,14 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) # UDP/IPv4 -udpSocketTransport = udp.UdpAsyncioTransport().openClientMode(allow_broadcast=True) -transportDispatcher.registerTransport(udp.DOMAIN_NAME, udpSocketTransport) +udpSocketTransport = udp.UdpAsyncioTransport().open_client_mode(allow_broadcast=True) +transportDispatcher.register_transport(udp.DOMAIN_NAME, udpSocketTransport) # Pass message to dispatcher -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(reqMsg), udp.DOMAIN_NAME, ("255.255.255.255", 161) ) @@ -89,4 +89,4 @@ def cbRecvFun( except: raise finally: - transportDispatcher.closeDispatcher() + transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/cmdgen/fetch-scalar-value.py b/examples/v1arch/asyncio/manager/cmdgen/fetch-scalar-value.py index 588296972..142b9c39f 100644 --- a/examples/v1arch/asyncio/manager/cmdgen/fetch-scalar-value.py +++ b/examples/v1arch/asyncio/manager/cmdgen/fetch-scalar-value.py @@ -63,15 +63,15 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # Pass message to dispatcher -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(reqMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 161) ) transportDispatcher.jobStarted(1) @@ -90,4 +90,4 @@ def cbRecvFun( # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/cmdgen/getbulk-pull-whole-mib.py b/examples/v1arch/asyncio/manager/cmdgen/getbulk-pull-whole-mib.py index e91a1334d..fc0c1c416 100644 --- a/examples/v1arch/asyncio/manager/cmdgen/getbulk-pull-whole-mib.py +++ b/examples/v1arch/asyncio/manager/cmdgen/getbulk-pull-whole-mib.py @@ -103,13 +103,13 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(reqMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 161) ) @@ -118,4 +118,4 @@ def cbRecvFun( # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/cmdgen/getnext-pull-whole-mib.py b/examples/v1arch/asyncio/manager/cmdgen/getnext-pull-whole-mib.py index 702e7a7d7..f4e1788e2 100644 --- a/examples/v1arch/asyncio/manager/cmdgen/getnext-pull-whole-mib.py +++ b/examples/v1arch/asyncio/manager/cmdgen/getnext-pull-whole-mib.py @@ -95,13 +95,13 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(reqMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 161) ) @@ -109,4 +109,4 @@ def cbRecvFun( transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/cmdgen/v2c-set.py b/examples/v1arch/asyncio/manager/cmdgen/v2c-set.py index 68653ca4e..69379a347 100644 --- a/examples/v1arch/asyncio/manager/cmdgen/v2c-set.py +++ b/examples/v1arch/asyncio/manager/cmdgen/v2c-set.py @@ -69,15 +69,15 @@ def cbRecvFun( transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbRecvFun) +transportDispatcher.register_recv_callback(cbRecvFun) # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # Pass message to dispatcher -transportDispatcher.sendMessage( +transportDispatcher.send_message( encoder.encode(reqMsg), udp.DOMAIN_NAME, ("demo.pysnmp.com", 161) ) @@ -86,4 +86,4 @@ def cbRecvFun( # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher(3) -transportDispatcher.closeDispatcher() +transportDispatcher.close_dispatcher() diff --git a/examples/v1arch/asyncio/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v1arch/asyncio/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py index ea90cc5bb..6bcaa324c 100644 --- a/examples/v1arch/asyncio/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py +++ b/examples/v1arch/asyncio/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py @@ -85,28 +85,28 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): transportDispatcher = AsyncioDispatcher() -transportDispatcher.registerRecvCbFun(cbFun) +transportDispatcher.register_recv_callback(cbFun) # UDP/IPv4 -transportDispatcher.registerTransport( - udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openServerMode(("localhost", 162)) +transportDispatcher.register_transport( + udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_server_mode(("localhost", 162)) ) # UDP/IPv6 -transportDispatcher.registerTransport( - udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().openServerMode(("::1", 162)) +transportDispatcher.register_transport( + udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().open_server_mode(("::1", 162)) ) -transportDispatcher.jobStarted(1) +transportDispatcher.job_started(1) try: print("This program needs to run as root/administrator to monitor port 162.") print("Started. Press Ctrl-C to stop") # Dispatcher will never finish as job#1 never reaches zero - transportDispatcher.runDispatcher() + transportDispatcher.run_dispatcher() except KeyboardInterrupt: print("Shutting down...") finally: - transportDispatcher.closeDispatcher() + transportDispatcher.close_dispatcher() diff --git a/examples/v3arch/asyncio/agent/cmdrsp/alternative-mib-tree.py b/examples/v3arch/asyncio/agent/cmdrsp/alternative-mib-tree.py index 017d60dd7..099a94f80 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/alternative-mib-tree.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/alternative-mib-tree.py @@ -30,17 +30,17 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-md5-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -64,11 +64,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/custom-mib-controller.py b/examples/v3arch/asyncio/agent/cmdrsp/custom-mib-controller.py index ffc2865d1..36319790c 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/custom-mib-controller.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/custom-mib-controller.py @@ -29,17 +29,17 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-none-none, auth: NONE, priv NONE -config.addV3User(snmpEngine, "usr-none-none") +config.add_v3_user(snmpEngine, "usr-none-none") # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-none-none", @@ -56,7 +56,7 @@ # any Managed Objects attached. It supports only GET's and # always echos request var-binds in response. class EchoMibInstrumController(instrum.AbstractMibInstrumController): - def readVars(self, *varBinds, **context): + def read_variables(self, *varBinds, **context): return [ (ov[0], v2c.OctetString("You queried OID %s" % ov[0])) for ov in varBinds ] @@ -74,11 +74,11 @@ def readVars(self, *varBinds, **context): cmdrsp.SetCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/custom-snmp-engine-id.py b/examples/v3arch/asyncio/agent/cmdrsp/custom-snmp-engine-id.py index 3cfac5471..1d4b77051 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/custom-snmp-engine-id.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/custom-snmp-engine-id.py @@ -27,14 +27,14 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -44,7 +44,7 @@ ) # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -58,11 +58,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/detailed-vacm-configuration.py b/examples/v3arch/asyncio/agent/cmdrsp/detailed-vacm-configuration.py index ec61e737b..4ecbbf9e2 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/detailed-vacm-configuration.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/detailed-vacm-configuration.py @@ -41,8 +41,8 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # Register default MIB instrumentation controller with a new SNMP context @@ -52,7 +52,7 @@ snmpContext = context.SnmpContext(snmpEngine) snmpContext.registerContextName( - contextName, snmpEngine.msgAndPduDsp.mibInstrumController + contextName, snmpEngine.message_dispatcher.mib_instrum_controller ) # Add new SNMP community name, map it to a new security name and @@ -61,7 +61,7 @@ securityName = "my-area" communityName = "public" -config.addV1System( +config.add_v1_system( snmpEngine, securityName, communityName, @@ -81,13 +81,13 @@ contextPrefix = contextName[:1] # Populate SNMP-VIEW-BASED-ACM-MIB::vacmContextTable -config.addContext(snmpEngine, contextName) +config.add_context(snmpEngine, contextName) # Populate SNMP-VIEW-BASED-ACM-MIB::vacmSecurityToGroupTable -config.addVacmGroup(snmpEngine, vacmGroup, securityModel, securityName) +config.add_vacm_group(snmpEngine, vacmGroup, securityModel, securityName) # Populate SNMP-VIEW-BASED-ACM-MIB::vacmAccessTable -config.addVacmAccess( +config.add_vacm_access( snmpEngine, vacmGroup, contextPrefix, @@ -102,12 +102,12 @@ # Populate SNMP-VIEW-BASED-ACM-MIB::vacmViewTreeFamilyTable # Allow the whole system subtree -config.addVacmView( +config.add_vacm_view( 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( +config.add_vacm_view( snmpEngine, readViewName, "excluded", "1.3.6.1.2.1.1.3", "1.1.1.1.1.1.1.1" ) @@ -117,12 +117,12 @@ cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except Exception: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects.py b/examples/v3arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects.py index 3dc1e26f2..ecb90faf3 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/implementing-scalar-mib-objects.py @@ -28,24 +28,24 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(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.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 5)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- create custom Managed Object Instance --- -mibBuilder = snmpContext.getMibInstrum().getMibBuilder() +mibBuilder = snmpContext.getMibInstrum().mibBuilder MibScalar, MibScalarInstance = mibBuilder.importSymbols( "SNMPv2-SMI", "MibScalar", "MibScalarInstance" @@ -74,11 +74,11 @@ def getValue(self, name, idx): cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/implementing-snmp-table.py b/examples/v3arch/asyncio/agent/cmdrsp/implementing-snmp-table.py index 913179883..ad3338da4 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/implementing-snmp-table.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/implementing-snmp-table.py @@ -36,24 +36,26 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(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.add_vacm_user( + snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 6), (1, 3, 6, 6) +) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- -mibBuilder = snmpContext.getMibInstrum().getMibBuilder() +mibBuilder = snmpContext.getMibInstrum().mibBuilder (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( "SNMPv2-SMI", "MibTable", "MibTableRow", "MibTableColumn", "MibScalarInstance" @@ -120,11 +122,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-custom-socket.py b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-custom-socket.py index a47e7c8dd..c56f207e8 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-custom-socket.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-custom-socket.py @@ -32,17 +32,17 @@ sock.bind(("::1", 161)) # This option is not available on many scenarios sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, socket.IPV6_V6ONLY) -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().openServerMode(sock=sock) +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().open_server_mode(sock=sock) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Allow full MIB access for this user / securityModels at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -56,11 +56,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py index bb42f6bbe..8ca2b4f6c 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py @@ -28,21 +28,21 @@ # Transport setup # UDP over IPv4 at 127.0.0.1:161 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # UDP over IPv6 at [::1]:161 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().openServerMode(("::1", 161)) +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().open_server_mode(("::1", 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Allow full MIB access for this user / securityModels at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -56,11 +56,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-multiple-interfaces.py b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-multiple-interfaces.py index 93dfca383..b0ecd4135 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/listen-on-multiple-interfaces.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/listen-on-multiple-interfaces.py @@ -27,25 +27,25 @@ # Transport setup # UDP over IPv4 at 127.0.0.1:161 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 161)), ) # UDP over IPv4 at 127.0.0.2:161 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (2,), - udp.UdpTransport().openServerMode(("127.0.0.2", 161)), + udp.UdpTransport().open_server_mode(("127.0.0.2", 161)), ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Allow full MIB access for this user / securityModels at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -59,11 +59,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-communities.py b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-communities.py index edb233437..5a30d867f 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-communities.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-communities.py @@ -28,8 +28,8 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv1 setup @@ -37,12 +37,12 @@ # 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.add_v1_system(snmpEngine, "my-read-area", "public") +config.add_v1_system(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( +config.add_vacm_user(snmpEngine, 1, "my-read-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1)) +config.add_vacm_user( snmpEngine, 1, "my-write-area", @@ -60,11 +60,11 @@ cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-contexts.py b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-contexts.py index 8c562adc2..855ea786d 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-contexts.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-contexts.py @@ -30,17 +30,17 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.domainName, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-md5-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -62,12 +62,12 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-engines.py b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-engines.py index 017568d8b..9f2ef2e60 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-engines.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/multiple-snmp-engines.py @@ -41,7 +41,7 @@ transportDispatcher = AsyncioDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain -transportDispatcher.registerRoutingCbFun(lambda td, t, d: td) +transportDispatcher.register_routing_callback(lambda td, t, d: td) # Instantiate and configure SNMP Engines for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo: @@ -50,19 +50,21 @@ # Register SNMP Engine object with transport dispatcher. Request incoming # data from specific transport endpoint to be funneled to this SNMP Engine. - snmpEngine.registerTransportDispatcher(transportDispatcher, transportDomain) + snmpEngine.register_transport_dispatcher(transportDispatcher, transportDomain) # Transport setup # UDP over IPv4 - config.addTransport( - snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) + config.add_transport( + snmpEngine, + transportDomain, + udp.UdpTransport().open_server_mode(transportAddress), ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES - config.addV3User( + config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -72,7 +74,7 @@ ) # Allow full MIB access for this user / securityModels at VACM - config.addVacmUser( + config.add_vacm_user( snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6), (1, 3, 6, 1, 2, 1) ) @@ -86,16 +88,16 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -transportDispatcher.jobStarted(1) +transportDispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: print("This program needs to run as root/administrator to monitor port 161.") print("Started. Press Ctrl-C to stop") - transportDispatcher.runDispatcher() + transportDispatcher.run_dispatcher() except KeyboardInterrupt: print("Shutting down...") finally: - transportDispatcher.closeDispatcher() + transportDispatcher.close_dispatcher() diff --git a/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py b/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py index 3a00d8d43..6df6fac16 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py @@ -29,14 +29,14 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -45,9 +45,9 @@ "privkey1", ) # user: usr-sha-none, auth: SHA, priv NONE -config.addV3User(snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1") +config.add_v3_user(snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1") # user: usr-sha-aes128, auth: SHA, priv AES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-sha-aes128", config.USM_AUTH_HMAC96_SHA, @@ -57,13 +57,13 @@ ) # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-sha-aes128", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -77,11 +77,11 @@ cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/cmdrsp/observe-request-processing.py b/examples/v3arch/asyncio/agent/cmdrsp/observe-request-processing.py index 355e7a5b2..2eabd0027 100644 --- a/examples/v3arch/asyncio/agent/cmdrsp/observe-request-processing.py +++ b/examples/v3arch/asyncio/agent/cmdrsp/observe-request-processing.py @@ -61,14 +61,14 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -78,7 +78,7 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): ) # Allow full MIB access for each user at VACM -config.addVacmUser( +config.add_vacm_user( snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) ) @@ -92,12 +92,12 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) +snmpEngine.transport_dispatcher.job_started(1) # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: snmpEngine.observer.unregisterObserver() - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/agent/ntforg/multiple-different-notifications-at-once.py b/examples/v3arch/asyncio/agent/ntforg/multiple-different-notifications-at-once.py index 3ad1fb5b0..2cc735ef4 100644 --- a/examples/v3arch/asyncio/agent/ntforg/multiple-different-notifications-at-once.py +++ b/examples/v3arch/asyncio/agent/ntforg/multiple-different-notifications-at-once.py @@ -34,23 +34,23 @@ # SNMPv2c: # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds-1", "my-area", "noAuthNoPriv", 1) # SNMPv3: -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") -config.addTargetParams(snmpEngine, "my-creds-2", "usr-md5-none", "authNoPriv") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_target_parameters(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.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # First target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-1", udp.DOMAIN_NAME, @@ -59,7 +59,7 @@ tagList="all-my-managers", ) # Second target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-2", udp.DOMAIN_NAME, @@ -71,15 +71,15 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) +config.add_vacm_user(snmpEngine, 3, "usr-md5-none", "authNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -127,4 +127,4 @@ def cbFun( print("Notifications %s are scheduled to be sent" % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/send-custom-pdu.py b/examples/v3arch/asyncio/agent/ntforg/send-custom-pdu.py index 7e118e5a1..a7b6d2615 100644 --- a/examples/v3arch/asyncio/agent/ntforg/send-custom-pdu.py +++ b/examples/v3arch/asyncio/agent/ntforg/send-custom-pdu.py @@ -27,19 +27,19 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # Create named target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, ("127.0.0.1", 162), "my-creds" ) diff --git a/examples/v3arch/asyncio/agent/ntforg/send-inform-to-multiple-managers.py b/examples/v3arch/asyncio/agent/ntforg/send-inform-to-multiple-managers.py index ce3685e08..0e7c0c015 100644 --- a/examples/v3arch/asyncio/agent/ntforg/send-inform-to-multiple-managers.py +++ b/examples/v3arch/asyncio/agent/ntforg/send-inform-to-multiple-managers.py @@ -31,18 +31,18 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # First target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-1", udp.DOMAIN_NAME, @@ -51,7 +51,7 @@ tagList="all-my-managers", ) # Second target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-2", udp.DOMAIN_NAME, @@ -60,7 +60,7 @@ tagList="all-my-managers", ) # Third target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-3", udp.DOMAIN_NAME, @@ -72,14 +72,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -109,4 +109,4 @@ print("Notifications are scheduled to be sent") # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/send-notification-over-ipv4-and-ipv6.py b/examples/v3arch/asyncio/agent/ntforg/send-notification-over-ipv4-and-ipv6.py index 306433b95..90499ff6c 100644 --- a/examples/v3arch/asyncio/agent/ntforg/send-notification-over-ipv4-and-ipv6.py +++ b/examples/v3arch/asyncio/agent/ntforg/send-notification-over-ipv4-and-ipv6.py @@ -30,19 +30,19 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(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.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-1", udp.DOMAIN_NAME, @@ -52,10 +52,10 @@ ) # UDP/IPv6 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-2", udp6.DOMAIN_NAME, @@ -67,14 +67,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -104,4 +104,4 @@ print("Notification is scheduled to be sent") # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/send-packet-from-specific-address.py b/examples/v3arch/asyncio/agent/ntforg/send-packet-from-specific-address.py index 1b54b5e51..987a82f82 100644 --- a/examples/v3arch/asyncio/agent/ntforg/send-packet-from-specific-address.py +++ b/examples/v3arch/asyncio/agent/ntforg/send-packet-from-specific-address.py @@ -26,20 +26,20 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(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 # used to originate packets from particular local IP:port -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME, - udp.UdpAsyncioTransport().openClientMode(iface=("0.0.0.0", 61024)), + udp.UdpAsyncioTransport().open_client_mode(iface=("0.0.0.0", 61024)), ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -51,14 +51,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 1, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -84,4 +84,4 @@ print("Notification is scheduled to be sent") # Run I/O dispatcher which would send pending message and stop -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/send-trap-to-multiple-managers.py b/examples/v3arch/asyncio/agent/ntforg/send-trap-to-multiple-managers.py index 86072a4c7..a88eadf82 100644 --- a/examples/v3arch/asyncio/agent/ntforg/send-trap-to-multiple-managers.py +++ b/examples/v3arch/asyncio/agent/ntforg/send-trap-to-multiple-managers.py @@ -31,18 +31,18 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) # First target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-1", udp.DOMAIN_NAME, @@ -51,7 +51,7 @@ tagList="all-my-managers", ) # Second target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-2", udp.DOMAIN_NAME, @@ -60,7 +60,7 @@ tagList="all-my-managers", ) # Third target -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-3", udp.DOMAIN_NAME, @@ -71,14 +71,14 @@ # Specify what kind of notification should be sent (TRAP or INFORM) # to what targets (chosen by tag) and with what credentials. -config.addNotificationTarget( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -108,4 +108,4 @@ print("Notifications are scheduled to be sent") # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/usm-md5-none.py b/examples/v3arch/asyncio/agent/ntforg/usm-md5-none.py index 73d1c07c7..5d8aaf6c6 100644 --- a/examples/v3arch/asyncio/agent/ntforg/usm-md5-none.py +++ b/examples/v3arch/asyncio/agent/ntforg/usm-md5-none.py @@ -26,15 +26,15 @@ snmpEngine = engine.SnmpEngine() # Add USM user -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_target_parameters(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -46,14 +46,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 3, "usr-md5-none", "authNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -99,4 +99,4 @@ def cbFun( print("Notification %s scheduled to be sent" % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/v1-trap.py b/examples/v3arch/asyncio/agent/ntforg/v1-trap.py index 62877ab02..a33a7b3a0 100644 --- a/examples/v3arch/asyncio/agent/ntforg/v1-trap.py +++ b/examples/v3arch/asyncio/agent/ntforg/v1-trap.py @@ -30,17 +30,17 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -52,14 +52,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 1, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -98,4 +98,4 @@ print("Notification is scheduled to be sent") # Run I/O dispatcher which would send pending message and stop -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/v2c-inform.py b/examples/v3arch/asyncio/agent/ntforg/v2c-inform.py index b5bd40349..ba5ff9474 100644 --- a/examples/v3arch/asyncio/agent/ntforg/v2c-inform.py +++ b/examples/v3arch/asyncio/agent/ntforg/v2c-inform.py @@ -28,17 +28,17 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping (+ transport binding) -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -50,14 +50,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -106,4 +106,4 @@ def cbFun( print("Notification %s scheduled to be sent" % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/v2c-trap-with-notification-objects.py b/examples/v3arch/asyncio/agent/ntforg/v2c-trap-with-notification-objects.py index 6895534e7..daf1f34ff 100644 --- a/examples/v3arch/asyncio/agent/ntforg/v2c-trap-with-notification-objects.py +++ b/examples/v3arch/asyncio/agent/ntforg/v2c-trap-with-notification-objects.py @@ -49,22 +49,22 @@ snmpEngine = engine.SnmpEngine() # MIB view controller is used for MIB lookup purposes -mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) +mibViewController = view.MibViewController(snmpEngine.get_mib_builder()) # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(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.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms-1", udp.DOMAIN_NAME, @@ -76,14 +76,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -106,4 +106,4 @@ print("Notification is scheduled to be sent") # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/v2c-trap.py b/examples/v3arch/asyncio/agent/ntforg/v2c-trap.py index b92b087bf..777948ea9 100644 --- a/examples/v3arch/asyncio/agent/ntforg/v2c-trap.py +++ b/examples/v3arch/asyncio/agent/ntforg/v2c-trap.py @@ -28,17 +28,17 @@ snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") +config.add_v1_system(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.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -50,14 +50,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -107,4 +107,4 @@ def cbFun( print("Notification %s is scheduled to be sent" % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/agent/ntforg/v3-trap.py b/examples/v3arch/asyncio/agent/ntforg/v3-trap.py index 72f53bc67..bdd3a40a4 100644 --- a/examples/v3arch/asyncio/agent/ntforg/v3-trap.py +++ b/examples/v3arch/asyncio/agent/ntforg/v3-trap.py @@ -30,7 +30,7 @@ ) # Add USM user -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -38,14 +38,14 @@ config.USM_PRIV_CBC56_DES, "privkey1", ) -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv") +config.add_target_parameters(snmpEngine, "my-creds", "usr-md5-des", "authPriv") # Setup transport endpoint and bind it with security settings yielding # a target name -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-nms", udp.DOMAIN_NAME, @@ -57,14 +57,14 @@ # 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( +config.add_notification_target( 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.add_context(snmpEngine, "") +config.add_vacm_user(snmpEngine, 3, "usr-md5-des", "authPriv", (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** @@ -93,4 +93,4 @@ print("Notification is scheduled to be sent") # Run I/O dispatcher which would send pending message and process response -snmpEngine.openDispatcher() +snmpEngine.open_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/custom-contextengineid-and-contextname.py b/examples/v3arch/asyncio/manager/cmdgen/custom-contextengineid-and-contextname.py index d9316c507..c69325fb0 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/custom-contextengineid-and-contextname.py +++ b/examples/v3arch/asyncio/manager/cmdgen/custom-contextengineid-and-contextname.py @@ -30,8 +30,8 @@ # # user: usr-md5-none, auth: MD5, priv: NONE -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_target_parameters(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -39,10 +39,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -84,4 +84,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/custom-timeout-and-retries.py b/examples/v3arch/asyncio/manager/cmdgen/custom-timeout-and-retries.py index 229e98f87..a1b5e1b05 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/custom-timeout-and-retries.py +++ b/examples/v3arch/asyncio/manager/cmdgen/custom-timeout-and-retries.py @@ -27,10 +27,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # # Setup transport endpoint and bind it with security settings yielding @@ -38,10 +38,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, @@ -87,4 +87,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/fetch-variables-over-ipv6.py b/examples/v3arch/asyncio/manager/cmdgen/fetch-variables-over-ipv6.py index 5b0ddf8d8..743440f33 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/fetch-variables-over-ipv6.py +++ b/examples/v3arch/asyncio/manager/cmdgen/fetch-variables-over-ipv6.py @@ -27,8 +27,8 @@ # # user: usr-md5-des, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_target_parameters(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -36,10 +36,10 @@ # # UDP/IPv6 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6AsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp6.DOMAIN_NAME, ("::1", 161), "my-creds" ) @@ -82,4 +82,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py b/examples/v3arch/asyncio/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py index 5341bb40b..6dc7cbf80 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py +++ b/examples/v3arch/asyncio/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py @@ -28,7 +28,7 @@ # # user: usr-md5-des, auth: MD5, priv DES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -36,7 +36,7 @@ config.USM_PRIV_CBC56_DES, "privkey1", ) -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv") +config.add_target_parameters(snmpEngine, "my-creds", "usr-md5-des", "authPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -44,10 +44,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -92,4 +92,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/getbulk-multiple-oids-to-eom.py b/examples/v3arch/asyncio/manager/cmdgen/getbulk-multiple-oids-to-eom.py index 1f032d799..1a6402081 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/getbulk-multiple-oids-to-eom.py +++ b/examples/v3arch/asyncio/manager/cmdgen/getbulk-multiple-oids-to-eom.py @@ -27,10 +27,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # # Setup transport endpoint and bind it with security settings yielding @@ -38,10 +38,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -86,4 +86,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py b/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py index d644c81ab..434f9eec1 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py +++ b/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py @@ -25,12 +25,12 @@ # Attach MIB compiler to SNMP Engine (MIB Builder) # This call will fail if PySMI is not present on the system -compiler.addMibCompiler(snmpEngine.getMibBuilder()) +compiler.addMibCompiler(snmpEngine.get_mib_builder()) # ... alternatively, this call will not complain on missing PySMI # compiler.addMibCompiler(snmpEngine.getMibBuilder(), ifAvailable=True) # Used for MIB objects resolution -mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) +mibViewController = view.MibViewController(snmpEngine.get_mib_builder()) # # @@ -38,10 +38,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # # Setup transport endpoint and bind it with security settings yielding @@ -49,10 +49,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -108,4 +108,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-to-eom.py b/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-to-eom.py index 72114168f..38877c7d6 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-to-eom.py +++ b/examples/v3arch/asyncio/manager/cmdgen/getnext-multiple-oids-to-eom.py @@ -27,10 +27,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) # # Setup transport endpoint and bind it with security settings yielding @@ -38,10 +38,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -86,4 +86,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/observe-request-processing.py b/examples/v3arch/asyncio/manager/cmdgen/observe-request-processing.py index 0ee10c7b5..15cc5d594 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/observe-request-processing.py +++ b/examples/v3arch/asyncio/manager/cmdgen/observe-request-processing.py @@ -65,7 +65,7 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): # # user: usr-sha-aes, auth: SHA, priv AES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-sha-aes", config.USM_AUTH_HMAC96_SHA, @@ -73,7 +73,7 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): config.USM_PRIV_CFB128_AES, "privkey1", ) -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") +config.add_target_parameters(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -81,10 +81,10 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -126,4 +126,4 @@ def cbFun( snmpEngine.observer.unregisterObserver() -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/pull-subtree.py b/examples/v3arch/asyncio/manager/cmdgen/pull-subtree.py index 27d0eceaf..9c73c9542 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/pull-subtree.py +++ b/examples/v3arch/asyncio/manager/cmdgen/pull-subtree.py @@ -30,11 +30,11 @@ # # user: usr-none-none, auth: none, priv: none -config.addV3User( +config.add_v3_user( snmpEngine, "usr-none-none", ) -config.addTargetParams(snmpEngine, "my-creds", "usr-none-none", "noAuthNoPriv") +config.add_target_parameters(snmpEngine, "my-creds", "usr-none-none", "noAuthNoPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -42,10 +42,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -91,4 +91,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/send-packets-from-specific-interface.py b/examples/v3arch/asyncio/manager/cmdgen/send-packets-from-specific-interface.py index e9aca9d1b..25dc06880 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/send-packets-from-specific-interface.py +++ b/examples/v3arch/asyncio/manager/cmdgen/send-packets-from-specific-interface.py @@ -28,10 +28,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) # # Setup transport endpoint and bind it with security settings yielding @@ -39,12 +39,12 @@ # # UDP/IPv4 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME, - udp.UdpAsyncioTransport().openClientMode(("0.0.0.0", 61024)), + udp.UdpAsyncioTransport().open_client_mode(("0.0.0.0", 61024)), ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -87,4 +87,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/set-multiple-scalar-values.py b/examples/v3arch/asyncio/manager/cmdgen/set-multiple-scalar-values.py index 9cfc3d4f4..05fbc6dfe 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/set-multiple-scalar-values.py +++ b/examples/v3arch/asyncio/manager/cmdgen/set-multiple-scalar-values.py @@ -27,10 +27,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "private") +config.add_v1_system(snmpEngine, "my-area", "private") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) # # Setup transport endpoint and bind it with security settings yielding @@ -38,10 +38,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -86,4 +86,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/usm-sha-aes128.py b/examples/v3arch/asyncio/manager/cmdgen/usm-sha-aes128.py index 3381124f1..89437c175 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/usm-sha-aes128.py +++ b/examples/v3arch/asyncio/manager/cmdgen/usm-sha-aes128.py @@ -25,7 +25,7 @@ # # user: usr-sha-aes, auth: SHA, priv AES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-sha-aes", config.USM_AUTH_HMAC96_SHA, @@ -33,7 +33,7 @@ config.USM_PRIV_CFB128_AES, "privkey1", ) -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") +config.add_target_parameters(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -41,10 +41,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -84,4 +84,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/usm-sha-none.py b/examples/v3arch/asyncio/manager/cmdgen/usm-sha-none.py index 6d921aa74..2e0849e89 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/usm-sha-none.py +++ b/examples/v3arch/asyncio/manager/cmdgen/usm-sha-none.py @@ -27,8 +27,8 @@ # # user: usr-sha-none, auth: SHA, priv none -config.addV3User(snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-none", "authNoPriv") +config.add_v3_user(snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1") +config.add_target_parameters(snmpEngine, "my-creds", "usr-sha-none", "authNoPriv") # # Setup transport endpoint and bind it with security settings yielding @@ -36,10 +36,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -79,4 +79,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/v1-get.py b/examples/v3arch/asyncio/manager/cmdgen/v1-get.py index e1d9b43f3..635d5e360 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/v1-get.py +++ b/examples/v3arch/asyncio/manager/cmdgen/v1-get.py @@ -24,10 +24,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) # # Setup transport endpoint and bind it with security settings yielding @@ -35,10 +35,10 @@ # # UDP/IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpAsyncioTransport().open_client_mode() ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -80,4 +80,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/cmdgen/v2c-set.py b/examples/v3arch/asyncio/manager/cmdgen/v2c-set.py index b1cd34eae..bfb402473 100644 --- a/examples/v3arch/asyncio/manager/cmdgen/v2c-set.py +++ b/examples/v3arch/asyncio/manager/cmdgen/v2c-set.py @@ -26,10 +26,10 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "private") +config.add_v1_system(snmpEngine, "my-area", "private") # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) +config.add_target_parameters(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) # # Setup transport endpoint and bind it with security settings yielding @@ -37,8 +37,8 @@ # # UDP/IPv4 -config.addTransport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openClientMode()) -config.addTargetAddr( +config.add_transport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_client_mode()) +config.add_target_address( snmpEngine, "my-router", udp.DOMAIN_NAME, ("127.0.0.1", 161), "my-creds" ) @@ -78,4 +78,4 @@ def cbFun( # Run I/O dispatcher which would send pending queries and process responses snmpEngine.openDispatcher(3) -snmpEngine.closeDispatcher() +snmpEngine.close_dispatcher() diff --git a/examples/v3arch/asyncio/manager/ntfrcv/determine-peer-network-address.py b/examples/v3arch/asyncio/manager/ntfrcv/determine-peer-network-address.py index f0e424274..ff370a9d9 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/determine-peer-network-address.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/determine-peer-network-address.py @@ -27,16 +27,16 @@ # Transport setup # UDP over IPv4, first listening interface/port -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 162)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 162)), ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Callback function for receiving notifications @@ -62,11 +62,11 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-interfaces.py b/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-interfaces.py index f5bd7c5d9..f274346fc 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-interfaces.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-interfaces.py @@ -28,23 +28,23 @@ # Transport setup # UDP over IPv4, first listening interface/port -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 162)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 162)), ) # UDP over IPv4, second listening interface/port -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (2,), - udp.UdpTransport().openServerMode(("127.0.0.1", 2162)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 2162)), ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Callback function for receiving notifications @@ -62,11 +62,11 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py b/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py index 729fd530d..ed5cac8b8 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py @@ -29,19 +29,19 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 162)) ) # UDP over IPv6 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().openServerMode(("::1", 162)) +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().open_server_mode(("::1", 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Callback function for receiving notifications @@ -59,11 +59,11 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/manager/ntfrcv/multiple-usm-users.py b/examples/v3arch/asyncio/manager/ntfrcv/multiple-usm-users.py index 669b12fa6..3a2ea1fe6 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/multiple-usm-users.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/multiple-usm-users.py @@ -38,15 +38,15 @@ # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 162)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -58,7 +58,7 @@ # user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, @@ -68,7 +68,7 @@ # user: usr-md5-aes256, auth: MD5, priv AES-256, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-aes256", config.USM_AUTH_HMAC96_MD5, @@ -80,7 +80,7 @@ # user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes -config.addV3User( +config.add_v3_user( snmpEngine, "usr-sha-aes128", config.USM_AUTH_HMAC96_SHA, @@ -105,11 +105,11 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py b/examples/v3arch/asyncio/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py index b643d50ac..b37d8bb9e 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py @@ -59,19 +59,19 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 162)) ) # UDP over IPv6 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().openServerMode(("::1", 162)) +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().open_server_mode(("::1", 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Callback function for receiving notifications @@ -89,12 +89,12 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: snmpEngine.observer.unregisterObserver() - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/manager/ntfrcv/regexp-community-name.py b/examples/v3arch/asyncio/manager/ntfrcv/regexp-community-name.py index ea6b2869c..ae11ac071 100644 --- a/examples/v3arch/asyncio/manager/ntfrcv/regexp-community-name.py +++ b/examples/v3arch/asyncio/manager/ntfrcv/regexp-community-name.py @@ -59,14 +59,14 @@ def requestObserver(snmpEngine, execpoint, variables, cbCtx): # Transport setup # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) +config.add_transport( + snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_server_mode(("127.0.0.1", 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # Callback function for receiving notifications @@ -84,11 +84,11 @@ def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cb # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/proxy/command/ipv6-to-ipv4-conversion.py b/examples/v3arch/asyncio/proxy/command/ipv6-to-ipv4-conversion.py index 625111ef5..31b3c5d56 100644 --- a/examples/v3arch/asyncio/proxy/command/ipv6-to-ipv4-conversion.py +++ b/examples/v3arch/asyncio/proxy/command/ipv6-to-ipv4-conversion.py @@ -41,21 +41,21 @@ # Agent section # UDP over IPv6 -config.addTransport( - snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().openServerMode(("::1", 161)) +config.add_transport( + snmpEngine, udp6.DOMAIN_NAME, udp6.Udp6Transport().open_server_mode(("::1", 161)) ) # Manager section # UDP over IPv4 -config.addTransport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openClientMode()) +config.add_transport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().open_client_mode()) # # SNMPv1/2c setup (Agent role) # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "1-my-area", "public") +config.add_v1_system(snmpEngine, "1-my-area", "public") # # SNMPv1/v2c setup (Manager role) @@ -64,16 +64,16 @@ # to let it match first in snmpCommunityTable on response processing. # -config.addV1System(snmpEngine, "0-distant-area", "public", transportTag="remote") +config.add_v1_system(snmpEngine, "0-distant-area", "public", transportTag="remote") # # Transport target used by Manager # -config.addTargetParams( +config.add_target_parameters( snmpEngine, "distant-agent-auth", "0-distant-area", "noAuthNoPriv", 1 ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "distant-agent", udp.DOMAIN_NAME, @@ -84,7 +84,7 @@ ) # Default SNMP context -config.addContext(snmpEngine, "") +config.add_context(snmpEngine, "") class CommandResponder(cmdrsp.CommandResponderBase): @@ -131,11 +131,11 @@ def handleResponsePdu( CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/proxy/command/v2c-to-v1-conversion.py b/examples/v3arch/asyncio/proxy/command/v2c-to-v1-conversion.py index 0b7615415..f2377ce8b 100644 --- a/examples/v3arch/asyncio/proxy/command/v2c-to-v1-conversion.py +++ b/examples/v3arch/asyncio/proxy/command/v2c-to-v1-conversion.py @@ -41,17 +41,17 @@ # Agent section # UDP over IPv4 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 161)), ) # Manager section # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().open_client_mode() ) # @@ -59,25 +59,25 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # # SNMPv1 setup (Manager role) # # SecurityName <-> CommunityName <-> Transport mapping -config.addV1System(snmpEngine, "distant-area", "public", transportTag="distant") +config.add_v1_system(snmpEngine, "distant-area", "public", transportTag="distant") # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams( +config.add_target_parameters( snmpEngine, "distant-agent-auth", "distant-area", "noAuthNoPriv", 0 ) -config.addTargetAddr( +config.add_target_address( snmpEngine, "distant-agent", udp.DOMAIN_NAME + (2,), @@ -88,7 +88,7 @@ ) # Default SNMP context -config.addContext(snmpEngine, "") +config.add_context(snmpEngine, "") class CommandResponder(cmdrsp.CommandResponderBase): @@ -135,11 +135,11 @@ def handleResponsePdu( CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/proxy/command/v2c-to-v3-conversion.py b/examples/v3arch/asyncio/proxy/command/v2c-to-v3-conversion.py index 47deb279b..56ade78c8 100644 --- a/examples/v3arch/asyncio/proxy/command/v2c-to-v3-conversion.py +++ b/examples/v3arch/asyncio/proxy/command/v2c-to-v3-conversion.py @@ -40,17 +40,17 @@ # Agent section # UDP over IPv4 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 161)), ) # Manager section # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().open_client_mode() ) # @@ -58,21 +58,23 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(snmpEngine, "my-area", "public") # # SNMPv3/USM setup (Manager role) # # user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") +config.add_v3_user(snmpEngine, "usr-md5-none", config.USM_AUTH_HMAC96_MD5, "authkey1") # # Transport target used by Manager # -config.addTargetParams(snmpEngine, "distant-agent-auth", "usr-md5-none", "authNoPriv") -config.addTargetAddr( +config.add_target_parameters( + snmpEngine, "distant-agent-auth", "usr-md5-none", "authNoPriv" +) +config.add_target_address( snmpEngine, "distant-agent", udp.DOMAIN_NAME + (2,), @@ -82,7 +84,7 @@ ) # Default SNMP context -config.addContext(snmpEngine, "") +config.add_context(snmpEngine, "") class CommandResponder(cmdrsp.CommandResponderBase): @@ -129,11 +131,11 @@ def handleResponsePdu( CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/examples/v3arch/asyncio/proxy/command/v3-to-v2c-conversion.py b/examples/v3arch/asyncio/proxy/command/v3-to-v2c-conversion.py index 79ba69819..89f57110f 100644 --- a/examples/v3arch/asyncio/proxy/command/v3-to-v2c-conversion.py +++ b/examples/v3arch/asyncio/proxy/command/v3-to-v2c-conversion.py @@ -40,17 +40,17 @@ # Agent section # UDP over IPv4 -config.addTransport( +config.add_transport( snmpEngine, udp.DOMAIN_NAME + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), + udp.UdpTransport().open_server_mode(("127.0.0.1", 161)), ) # Manager section # UDP over IPv4 -config.addTransport( - snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().openClientMode() +config.add_transport( + snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().open_client_mode() ) # @@ -58,7 +58,7 @@ # # user: usr-md5-des, auth: MD5, priv DES -config.addV3User( +config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -72,16 +72,18 @@ # # SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") +config.add_v1_system(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.add_target_parameters( + snmpEngine, "distant-agent-auth", "my-area", "noAuthNoPriv", 0 +) -config.addTargetAddr( +config.add_target_address( snmpEngine, "distant-agent", udp.DOMAIN_NAME + (2,), @@ -91,7 +93,7 @@ ) # Default SNMP context -config.addContext(snmpEngine, "") +config.add_context(snmpEngine, "") class CommandResponder(cmdrsp.CommandResponderBase): @@ -138,11 +140,11 @@ def handleResponsePdu( CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transport_dispatcher.job_started(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() except: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() raise diff --git a/poetry.lock b/poetry.lock index 56b7a04f2..9f6540df8 100644 --- a/poetry.lock +++ b/poetry.lock @@ -849,6 +849,20 @@ files = [ {file = "pbr-6.1.0.tar.gz", hash = "sha256:788183e382e3d1d7707db08978239965e8b9e4e5ed42669bf4758186734d5f24"}, ] +[[package]] +name = "pep8-naming" +version = "0.14.1" +description = "Check PEP-8 naming conventions, plugin for flake8" +optional = false +python-versions = ">=3.8" +files = [ + {file = "pep8-naming-0.14.1.tar.gz", hash = "sha256:1ef228ae80875557eb6c1549deafed4dabbf3261cfcafa12f773fe0db9be8a36"}, + {file = "pep8_naming-0.14.1-py3-none-any.whl", hash = "sha256:63f514fc777d715f935faf185dedd679ab99526a7f2f503abb61587877f7b1c5"}, +] + +[package.dependencies] +flake8 = ">=5.0.0" + [[package]] name = "platformdirs" version = "4.3.6" @@ -1526,4 +1540,4 @@ type = ["pytest-mypy"] [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "125334006706ea3d55848fa3a408b60117c9ee26a7fd4518e55f7effd340a934" +content-hash = "6b7bb69e17cc850623a40dc5df008f5aab99a647d7ff50f5a77b604e32e9003c" diff --git a/pyproject.toml b/pyproject.toml index d4c0dd38d..d83dc3e42 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,7 @@ flake8-rst-docstrings = "^0.3.0" sphinx-polyversion = "^1.0.0" cryptography = "^43.0.1" pysmi = "^1.3.0" +pep8-naming = "^0.14.1" [tool.poetry_bumpversion.file."pysnmp/__init__.py"] diff --git a/pysnmp/carrier/asyncio/dgram/base.py b/pysnmp/carrier/asyncio/dgram/base.py index 2c1c83b7b..b6d01e91a 100644 --- a/pysnmp/carrier/asyncio/dgram/base.py +++ b/pysnmp/carrier/asyncio/dgram/base.py @@ -101,10 +101,12 @@ def __init__( def datagram_received(self, datagram, transportAddress: AbstractTransportAddress): """Process incoming datagram.""" - if self._cbFun is None: + if self._callback_function is None: raise error.CarrierError("Unable to call cbFun") else: - self.loop.call_soon(self._cbFun, self, transportAddress, datagram) + self.loop.call_soon( + self._callback_function, self, transportAddress, datagram + ) def connection_made(self, transport: asyncio.DatagramTransport): """Prepare to send datagrams.""" @@ -131,7 +133,7 @@ def connection_lost(self, exc): # AbstractAsyncioTransport API - def openClientMode( + def open_client_mode( self, iface: "tuple[str, int] | None" = None, allow_broadcast: bool = False ): """Open client mode.""" @@ -151,7 +153,7 @@ def openClientMode( ) return self - def openServerMode( + def open_server_mode( self, iface: "tuple[str, int] | None" = None, sock: "socket | None" = None ): """Open server mode.""" @@ -173,15 +175,15 @@ def openServerMode( ) return self - def closeTransport(self): + def close_transport(self): """Close the transport.""" if self._lport is not None: self._lport.cancel() if self.transport is not None: self.transport.close() - AbstractAsyncioTransport.closeTransport(self) + AbstractAsyncioTransport.close_transport(self) - def sendMessage( + def send_message( self, outgoingMessage, transportAddress: "AbstractTransportAddress | tuple[str, int]", diff --git a/pysnmp/carrier/asyncio/dispatch.py b/pysnmp/carrier/asyncio/dispatch.py index cb085c22c..15be6d9dc 100644 --- a/pysnmp/carrier/asyncio/dispatch.py +++ b/pysnmp/carrier/asyncio/dispatch.py @@ -54,45 +54,47 @@ def __init__(self, *args, **kwargs): AbstractTransportDispatcher.__init__(self) self.__transportCount = 0 if "timeout" in kwargs: - self.setTimerResolution(kwargs["timeout"]) + self.set_timer_resolution(kwargs["timeout"]) self.loopingcall = None self.loop = kwargs.pop("loop", asyncio.get_event_loop()) async def handle_timeout(self): """Handle timeout event.""" while True: - await asyncio.sleep(self.getTimerResolution()) - self.handleTimerTick(time()) + await asyncio.sleep(self.get_timer_resolution()) + self.handle_timer_tick(time()) - def runDispatcher(self, timeout: float = 0.0): + def run_dispatcher(self, timeout: float = 0.0): """Run the dispatcher loop.""" if not self.loop.is_running(): try: if timeout > 0: - self.loop.call_later(timeout, self.__closeDispatcher) + self.loop.call_later(timeout, self.__close_dispatcher) self.loop.run_forever() except KeyboardInterrupt: raise except Exception: raise PySnmpError(";".join(traceback.format_exception(*sys.exc_info()))) - def __closeDispatcher(self): + def __close_dispatcher(self): if self.loop.is_running(): self.loop.stop() - super().closeDispatcher() + super().close_dispatcher() - def registerTransport(self, tDomain: Tuple[int, ...], transport: AbstractTransport): + def register_transport( + self, tDomain: Tuple[int, ...], transport: AbstractTransport + ): """Register transport associated with given transport domain.""" - if self.loopingcall is None and self.getTimerResolution() > 0: + if self.loopingcall is None and self.get_timer_resolution() > 0: self.loopingcall = asyncio.ensure_future(self.handle_timeout()) - AbstractTransportDispatcher.registerTransport(self, tDomain, transport) + AbstractTransportDispatcher.register_transport(self, tDomain, transport) self.__transportCount += 1 - def unregisterTransport(self, tDomain: Tuple[int, ...]): + def unregister_transport(self, tDomain: Tuple[int, ...]): """Unregister transport associated with given transport domain.""" - t = AbstractTransportDispatcher.getTransport(self, tDomain) + t = AbstractTransportDispatcher.get_transport(self, tDomain) if t is not None: - AbstractTransportDispatcher.unregisterTransport(self, tDomain) + AbstractTransportDispatcher.unregister_transport(self, tDomain) self.__transportCount -= 1 # The last transport has been removed, stop the timeout diff --git a/pysnmp/carrier/base.py b/pysnmp/carrier/base.py index 5111c84d3..239c86047 100644 --- a/pysnmp/carrier/base.py +++ b/pysnmp/carrier/base.py @@ -53,19 +53,19 @@ class AbstractTransportAddress: _localAddress = None - def setLocalAddress(self, s): + def set_local_address(self, s): """Set the local address.""" self._localAddress = s return self - def getLocalAddress(self): + def get_local_address(self): """Return the local address.""" return self._localAddress def clone(self, localAddress=None): """Clone the address.""" - return self.__class__(self).setLocalAddress( - localAddress is None and self.getLocalAddress() or localAddress + return self.__class__(self).set_local_address( + localAddress is None and self.get_local_address() or localAddress ) @@ -74,10 +74,10 @@ class AbstractTransport: PROTO_TRANSPORT_DISPATCHER = None ADDRESS_TYPE = AbstractTransportAddress - _cbFun = None + _callback_function = None @classmethod - def isCompatibleWithDispatcher( + def is_compatible_with_dispatcher( cls, transportDispatcher: "AbstractTransportDispatcher" ): """Return True if the transport dispatcher is compatible.""" @@ -87,33 +87,33 @@ def isCompatibleWithDispatcher( ) return isinstance(transportDispatcher, cls.PROTO_TRANSPORT_DISPATCHER) - def registerCbFun(self, cbFun): + def register_callback(self, cbFun): """Register the callback function.""" - if self._cbFun: + if self._callback_function: raise error.CarrierError( - f"Callback function {self._cbFun} already registered at {self}" + f"Callback function {self._callback_function} already registered at {self}" ) - self._cbFun = cbFun + self._callback_function = cbFun - def unregisterCbFun(self): + def unregister_callback(self): """Unregister the callback function.""" - self._cbFun = None + self._callback_function = None - def closeTransport(self): + def close_transport(self): """Close the transport.""" - self.unregisterCbFun() + self.unregister_callback() # Public API - def openClientMode(self, iface: "tuple[str, int] | None" = None): + def open_client_mode(self, iface: "tuple[str, int] | None" = None): """Open client mode.""" raise error.CarrierError("Method not implemented") - def openServerMode(self, iface: "tuple[str, int]"): + def open_server_mode(self, iface: "tuple[str, int]"): """Open server mode.""" raise error.CarrierError("Method not implemented") - def sendMessage(self, outgoingMessage, transportAddress: AbstractTransportAddress): + def send_message(self, outgoingMessage, transportAddress: AbstractTransportAddress): """Send a message to the transport.""" raise error.CarrierError("Method not implemented") @@ -144,7 +144,7 @@ def __init__(self): self.__nextTime = 0 self.__routingCbFun = None - def _cbFun( + def _callback_function( self, incomingTransport: AbstractTransport, transportAddress: AbstractTransportAddress, @@ -173,7 +173,7 @@ def _cbFun( # Dispatcher API - def registerRoutingCbFun( + def register_routing_callback( self, routingCbFun: "Callable[[tuple[int, ...], AbstractTransportAddress, Any], 'tuple[int, ...]'] | None", ): @@ -182,12 +182,14 @@ def registerRoutingCbFun( raise error.CarrierError("Data routing callback already registered") self.__routingCbFun = routingCbFun - def unregisterRoutingCbFun(self): + def unregister_routing_callback(self): """Unregister a routing callback.""" if self.__routingCbFun: self.__routingCbFun = None - def registerRecvCbFun(self, recvCb, recvId: "tuple[int, ...] | str | None" = None): + def register_recv_callback( + self, recvCb, recvId: "tuple[int, ...] | str | None" = None + ): """Register a receive callback.""" if recvId in self.__recvCallables: raise error.CarrierError( @@ -197,12 +199,12 @@ def registerRecvCbFun(self, recvCb, recvId: "tuple[int, ...] | str | None" = Non ) self.__recvCallables[recvId] = recvCb - def unregisterRecvCbFun(self, recvId: "tuple[int, ...] | None" = None): + def unregister_recv_callback(self, recvId: "tuple[int, ...] | None" = None): """Unregister a receive callback.""" if recvId in self.__recvCallables: del self.__recvCallables[recvId] - def registerTimerCbFun( + def register_timer_callback( self, timerCbFun: Callable, tickInterval: "float | None" = None ): """Register a timer callback.""" @@ -210,38 +212,38 @@ def registerTimerCbFun( tickInterval = self.__timerResolution self.__timerCallables.append(TimerCallable(timerCbFun, tickInterval)) - def unregisterTimerCbFun(self, timerCbFun: "TimerCallable | None" = None): + def unregister_timer_callback(self, timerCbFun: "TimerCallable | None" = None): """Unregister a timer callback.""" if timerCbFun: self.__timerCallables.remove(timerCbFun) else: self.__timerCallables = [] - def registerTransport( + def register_transport( self, tDomain: "tuple[int, ...]", transport: AbstractTransport ): """Register a transport.""" if tDomain in self.__transports: raise error.CarrierError(f"Transport {tDomain} already registered") - transport.registerCbFun(self._cbFun) + transport.register_callback(self._callback_function) self.__transports[tDomain] = transport self.__transportDomainMap[transport] = tDomain - def unregisterTransport(self, tDomain: "tuple[int, ...]"): + def unregister_transport(self, tDomain: "tuple[int, ...]"): """Unregister a transport.""" if tDomain not in self.__transports: raise error.CarrierError(f"Transport {tDomain} not registered") - self.__transports[tDomain].unregisterCbFun() + self.__transports[tDomain].unregister_callback() del self.__transportDomainMap[self.__transports[tDomain]] del self.__transports[tDomain] - def getTransport(self, transportDomain: "tuple[int, ...]"): + def get_transport(self, transportDomain: "tuple[int, ...]"): """Return the transport object.""" if transportDomain in self.__transports: return self.__transports[transportDomain] raise error.CarrierError(f"Transport {transportDomain} not registered") - def sendMessage( + def send_message( self, outgoingMessage, transportDomain: "tuple[int, ...]", @@ -249,7 +251,7 @@ def sendMessage( ): """Send a message to the transport.""" if transportDomain in self.__transports: - self.__transports[transportDomain].sendMessage( + self.__transports[transportDomain].send_message( outgoingMessage, transportAddress ) else: @@ -257,11 +259,11 @@ def sendMessage( f"No suitable transport domain for {transportDomain}" ) - def getTimerResolution(self): + def get_timer_resolution(self): """Return the timer resolution.""" return self.__timerResolution - def setTimerResolution(self, timerResolution: float): + def set_timer_resolution(self, timerResolution: float): """Set the timer resolution.""" if timerResolution < 0.01 or timerResolution > 10: raise error.CarrierError("Impossible timer resolution") @@ -274,11 +276,11 @@ def setTimerResolution(self, timerResolution: float): self.__timerResolution = timerResolution self.__timerDelta = timerResolution * 0.05 - def getTimerTicks(self): + def get_timer_ticks(self): """Return the number of timer ticks.""" return self.__ticks - def handleTimerTick(self, timeNow: float): + def handle_timer_tick(self, timeNow: float): """Handle timer tick.""" if self.__nextTime == 0: # initial initialization self.__nextTime = timeNow + self.__timerResolution - self.__timerDelta @@ -292,32 +294,32 @@ def handleTimerTick(self, timeNow: float): for timerCallable in self.__timerCallables: timerCallable(timeNow) - def jobStarted(self, jobId, count: int = 1): + def job_started(self, jobId, count: int = 1): """Mark a job as started.""" if jobId in self.__jobs: self.__jobs[jobId] += count else: self.__jobs[jobId] = count - def jobFinished(self, jobId, count: int = 1): + def job_finished(self, jobId, count: int = 1): """Mark a job as finished.""" self.__jobs[jobId] -= count if self.__jobs[jobId] == 0: del self.__jobs[jobId] - def jobsArePending(self): + def jobs_are_pending(self): """Return True if there are pending jobs.""" return bool(self.__jobs) - def runDispatcher(self, timeout: float = 0.0): + def run_dispatcher(self, timeout: float = 0.0): """Run the dispatcher.""" raise error.CarrierError("Method not implemented") - def closeDispatcher(self): + def close_dispatcher(self): """Close the dispatcher.""" for tDomain in list(self.__transports): - self.__transports[tDomain].closeTransport() - self.unregisterTransport(tDomain) + self.__transports[tDomain].close_transport() + self.unregister_transport(tDomain) self.__transports.clear() - self.unregisterRecvCbFun() - self.unregisterTimerCbFun() + self.unregister_recv_callback() + self.unregister_timer_callback() diff --git a/pysnmp/debug.py b/pysnmp/debug.py index 85d45cd03..d2c2c655f 100644 --- a/pysnmp/debug.py +++ b/pysnmp/debug.py @@ -182,7 +182,7 @@ def __rand__(self, flag): logger = 0 -def setLogger(value): +def set_logger(value): """Set the global logger.""" global logger logger = value diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py index fb22b2725..2d122658d 100644 --- a/pysnmp/entity/config.py +++ b/pysnmp/entity/config.py @@ -15,6 +15,7 @@ from pysnmp.proto.secmod.eso.priv import aes192, aes256, des3 from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth from pysnmp.proto.secmod.rfc3414.priv import des, nopriv +from pysnmp.proto.secmod.rfc3414.service import SnmpUSMSecurityModel from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.rfc7860.auth import hmacsha2 @@ -94,49 +95,24 @@ def __getattr__(attr: str): USM_KEY_TYPE_LOCALIZED = 2 # Auth services -AUTH_SERVICES = { - hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(), - hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(), - hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2( - hmacsha2.HmacSha2.SHA224_SERVICE_ID - ), - hmacsha2.HmacSha2.SHA256_SERVICE_ID: hmacsha2.HmacSha2( - hmacsha2.HmacSha2.SHA256_SERVICE_ID - ), - hmacsha2.HmacSha2.SAH384_SERVICE_ID: hmacsha2.HmacSha2( - hmacsha2.HmacSha2.SAH384_SERVICE_ID - ), - hmacsha2.HmacSha2.SHA512_SERVICE_ID: hmacsha2.HmacSha2( - hmacsha2.HmacSha2.SHA512_SERVICE_ID - ), - noauth.NoAuth.SERVICE_ID: noauth.NoAuth(), -} +AUTH_SERVICES = SnmpUSMSecurityModel.AUTH_SERVICES # Privacy services -PRIV_SERVICES = { - des.Des.SERVICE_ID: des.Des(), - des3.Des3.SERVICE_ID: des3.Des3(), - aes.Aes.SERVICE_ID: aes.Aes(), - aes192.AesBlumenthal192.SERVICE_ID: aes192.AesBlumenthal192(), - aes256.AesBlumenthal256.SERVICE_ID: aes256.AesBlumenthal256(), - aes192.Aes192.SERVICE_ID: aes192.Aes192(), # non-standard - aes256.Aes256.SERVICE_ID: aes256.Aes256(), # non-standard - nopriv.NoPriv.SERVICE_ID: nopriv.NoPriv(), -} +PRIV_SERVICES = SnmpUSMSecurityModel.PRIV_SERVICES -def __cookV1SystemInfo(snmpEngine: SnmpEngine, communityIndex): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_v1_system_info(snmpEngine: SnmpEngine, communityIndex): + mibBuilder = snmpEngine.get_mib_builder() - (snmpEngineID,) = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID") - (snmpCommunityEntry,) = mibBuilder.importSymbols( + (snmpEngineID,) = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID") # type: ignore + (snmpCommunityEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-COMMUNITY-MIB", "snmpCommunityEntry" ) tblIdx = snmpCommunityEntry.getInstIdFromIndices(communityIndex) return snmpCommunityEntry, tblIdx, snmpEngineID -def addV1System( +def add_v1_system( snmpEngine: SnmpEngine, communityIndex: str, communityName: str, @@ -146,7 +122,7 @@ def addV1System( securityName=None, ): """Register SNMPv1 and v2c community.""" - (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo( + (snmpCommunityEntry, tblIdx, snmpEngineID) = __cook_v1_system_info( snmpEngine, communityIndex ) @@ -160,11 +136,11 @@ def addV1System( securityName = securityName is not None and securityName or communityIndex - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpCommunityEntry.name + (8,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpCommunityEntry.name + (1,) + tblIdx, communityIndex), (snmpCommunityEntry.name + (2,) + tblIdx, communityName), ( @@ -195,12 +171,12 @@ def addV1System( ) -def delV1System(snmpEngine, communityIndex): +def delete_v1_system(snmpEngine: SnmpEngine, communityIndex): """Unregister SNMPv1 and v2c community.""" - (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo( + (snmpCommunityEntry, tblIdx, snmpEngineID) = __cook_v1_system_info( snmpEngine, communityIndex ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpCommunityEntry.name + (8,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) @@ -210,20 +186,20 @@ def delV1System(snmpEngine, communityIndex): ) -def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_v3_user_info(snmpEngine: SnmpEngine, securityName, securityEngineId): + mibBuilder = snmpEngine.get_mib_builder() - (snmpEngineID,) = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID") + (snmpEngineID,) = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID") # type: ignore if securityEngineId is None: securityEngineId = snmpEngineID.syntax else: securityEngineId = snmpEngineID.syntax.clone(securityEngineId) - (usmUserEntry,) = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") + (usmUserEntry,) = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") # type: ignore tblIdx1 = usmUserEntry.getInstIdFromIndices(securityEngineId, securityName) - (pysnmpUsmSecretEntry,) = mibBuilder.importSymbols( + (pysnmpUsmSecretEntry,) = mibBuilder.importSymbols( # type: ignore "PYSNMP-USM-MIB", "pysnmpUsmSecretEntry" ) tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) @@ -231,8 +207,8 @@ def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): return securityEngineId, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 -def addV3User( - snmpEngine, +def add_v3_user( + snmpEngine: SnmpEngine, userName, authProtocol=USM_AUTH_NONE, authKey=None, @@ -244,7 +220,7 @@ def addV3User( privKeyType=USM_KEY_TYPE_PASSPHRASE, ): """Register SNMPv3 user.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() if securityName is None: securityName = userName @@ -255,20 +231,20 @@ def addV3User( tblIdx1, pysnmpUsmSecretEntry, tblIdx2, - ) = __cookV3UserInfo(snmpEngine, securityName, securityEngineId) + ) = __cook_v3_user_info(snmpEngine, securityName, securityEngineId) # Load augmenting table before creating new row in base one - (pysnmpUsmKeyEntry,) = mibBuilder.importSymbols( + (pysnmpUsmKeyEntry,) = mibBuilder.importSymbols( # type: ignore "PYSNMP-USM-MIB", "pysnmpUsmKeyEntry" ) # Load clone-from (may not be needed) - (zeroDotZero,) = mibBuilder.importSymbols("SNMPv2-SMI", "zeroDotZero") + (zeroDotZero,) = mibBuilder.importSymbols("SNMPv2-SMI", "zeroDotZero") # type: ignore - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (usmUserEntry.name + (13,) + tblIdx1, "destroy"), **dict(snmpEngine=snmpEngine) ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (usmUserEntry.name + (2,) + tblIdx1, userName), (usmUserEntry.name + (3,) + tblIdx1, securityName), (usmUserEntry.name + (4,) + tblIdx1, zeroDotZero.name), @@ -284,7 +260,7 @@ def addV3User( if privProtocol not in PRIV_SERVICES: raise error.PySnmpError(f"Unknown privacy protocol {privProtocol}") - (pysnmpUsmKeyType,) = mibBuilder.importSymbols( + (pysnmpUsmKeyType,) = mibBuilder.importSymbols( # type: ignore "__PYSNMP-USM-MIB", "pysnmpUsmKeyType" ) @@ -297,10 +273,10 @@ def addV3User( masterAuthKey = localAuthKey = authKey if authKeyType < USM_KEY_TYPE_MASTER: # pass phrase is given - masterAuthKey = AUTH_SERVICES[authProtocol].hashPassphrase(authKey or b"") + masterAuthKey = AUTH_SERVICES[authProtocol].hash_passphrase(authKey or b"") if authKeyType < USM_KEY_TYPE_LOCALIZED: # pass phrase or master key is given - localAuthKey = AUTH_SERVICES[authProtocol].localizeKey( + localAuthKey = AUTH_SERVICES[authProtocol].localize_key( masterAuthKey, securityEngineId ) @@ -313,56 +289,56 @@ def addV3User( masterPrivKey = localPrivKey = privKey if privKeyType < USM_KEY_TYPE_MASTER: # pass phrase is given - masterPrivKey = PRIV_SERVICES[privProtocol].hashPassphrase( + masterPrivKey = PRIV_SERVICES[privProtocol].hash_passphrase( authProtocol, privKey or b"" ) if privKeyType < USM_KEY_TYPE_LOCALIZED: # pass phrase or master key is given - localPrivKey = PRIV_SERVICES[privProtocol].localizeKey( + localPrivKey = PRIV_SERVICES[privProtocol].localize_key( authProtocol, masterPrivKey, securityEngineId ) # Commit only the keys we have - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmKeyEntry.name + (1,) + tblIdx1, localAuthKey), (pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey), **dict(snmpEngine=snmpEngine), ) if authKeyType < USM_KEY_TYPE_LOCALIZED: - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmKeyEntry.name + (3,) + tblIdx1, masterAuthKey), **dict(snmpEngine=snmpEngine), ) if privKeyType < USM_KEY_TYPE_LOCALIZED: - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmKeyEntry.name + (4,) + tblIdx1, masterPrivKey), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, "destroy"), **dict(snmpEngine=snmpEngine), ) # Commit plain-text pass-phrases if we have them - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, "createAndGo"), **dict(snmpEngine=snmpEngine), ) if authKeyType < USM_KEY_TYPE_MASTER: - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmSecretEntry.name + (1,) + tblIdx2, userName), (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), **dict(snmpEngine=snmpEngine), ) if privKeyType < USM_KEY_TYPE_MASTER: - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmSecretEntry.name + (1,) + tblIdx2, userName), (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey), **dict(snmpEngine=snmpEngine), @@ -392,8 +368,8 @@ def addV3User( ) -def delV3User( - snmpEngine, +def delete_v3_user( + snmpEngine: SnmpEngine, userName, securityEngineId=None, ): @@ -404,13 +380,13 @@ def delV3User( tblIdx1, pysnmpUsmSecretEntry, tblIdx2, - ) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) + ) = __cook_v3_user_info(snmpEngine, userName, securityEngineId) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (usmUserEntry.name + (13,) + tblIdx1, "destroy"), **dict(snmpEngine=snmpEngine) ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, "destroy"), **dict(snmpEngine=snmpEngine), ) @@ -429,7 +405,7 @@ def delV3User( ) while varBinds: - varBinds = snmpEngine.msgAndPduDsp.mibInstrumController.readNextVars( + varBinds = snmpEngine.message_dispatcher.mib_instrum_controller.readNextVars( *varBinds, **dict(snmpEngine=snmpEngine) ) if varBinds[0][1].isSameTypeWith(rfc1905.endOfMibView): @@ -437,14 +413,14 @@ def delV3User( if varBinds[0][0][: len(initialVarBinds[0][0])] != initialVarBinds[0][0]: break elif varBinds[2][1] == tblIdx1: # cloned from this entry - delV3User(snmpEngine, varBinds[1][1], varBinds[0][1]) + delete_v3_user(snmpEngine, varBinds[1][1], varBinds[0][1]) varBinds = initialVarBinds -def __cookTargetParamsInfo(snmpEngine, name): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_target_parameters_info(snmpEngine: SnmpEngine, name): + mibBuilder = snmpEngine.get_mib_builder() - (snmpTargetParamsEntry,) = mibBuilder.importSymbols( + (snmpTargetParamsEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-TARGET-MIB", "snmpTargetParamsEntry" ) tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) @@ -452,7 +428,9 @@ def __cookTargetParamsInfo(snmpEngine, name): # mpModel: 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 -def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): +def add_target_parameters( + snmpEngine: SnmpEngine, name, securityName, securityLevel, mpModel=3 +): """Register target parameters.""" if mpModel == 0: securityModel = 1 @@ -463,13 +441,13 @@ def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): else: raise error.PySnmpError("Unknown MP model %s" % mpModel) - snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) + snmpTargetParamsEntry, tblIdx = __cook_target_parameters_info(snmpEngine, name) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetParamsEntry.name + (7,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetParamsEntry.name + (1,) + tblIdx, name), (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), @@ -480,29 +458,29 @@ def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): ) -def delTargetParams(snmpEngine: SnmpEngine, name: str): +def delete_target_parameters(snmpEngine: SnmpEngine, name: str): """Delete target parameters.""" - snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpTargetParamsEntry, tblIdx = __cook_target_parameters_info(snmpEngine, name) + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetParamsEntry.name + (7,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) -def __cookTargetAddrInfo(snmpEngine: SnmpEngine, addrName: str): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_target_address_info(snmpEngine: SnmpEngine, addrName: str): + mibBuilder = snmpEngine.get_mib_builder() - (snmpTargetAddrEntry,) = mibBuilder.importSymbols( + (snmpTargetAddrEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-TARGET-MIB", "snmpTargetAddrEntry" ) - (snmpSourceAddrEntry,) = mibBuilder.importSymbols( + (snmpSourceAddrEntry,) = mibBuilder.importSymbols( # type: ignore "PYSNMP-SOURCE-MIB", "snmpSourceAddrEntry" ) tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx -def addTargetAddr( +def add_target_address( snmpEngine: SnmpEngine, addrName: str, transportDomain: "tuple[int, ...]", @@ -514,20 +492,20 @@ def addTargetAddr( sourceAddress=None, ): """Register target address.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() - (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo( + (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cook_target_address_info( snmpEngine, addrName ) if transportDomain[: len(SNMP_UDP_DOMAIN)] == SNMP_UDP_DOMAIN: - (SnmpUDPAddress,) = mibBuilder.importSymbols("SNMPv2-TM", "SnmpUDPAddress") + (SnmpUDPAddress,) = mibBuilder.importSymbols("SNMPv2-TM", "SnmpUDPAddress") # type: ignore transportAddress = SnmpUDPAddress(transportAddress) if sourceAddress is None: sourceAddress = ("0.0.0.0", 0) sourceAddress = SnmpUDPAddress(sourceAddress) elif transportDomain[: len(SNMP_UDP6_DOMAIN)] == SNMP_UDP6_DOMAIN: - (TransportAddressIPv6,) = mibBuilder.importSymbols( + (TransportAddressIPv6,) = mibBuilder.importSymbols( # type: ignore "TRANSPORT-ADDRESS-MIB", "TransportAddressIPv6" ) transportAddress = TransportAddressIPv6(transportAddress) @@ -535,11 +513,11 @@ def addTargetAddr( sourceAddress = ("::", 0) sourceAddress = TransportAddressIPv6(sourceAddress) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetAddrEntry.name + (9,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), (snmpTargetAddrEntry.name + (2,) + tblIdx, transportDomain), (snmpTargetAddrEntry.name + (3,) + tblIdx, transportAddress), @@ -553,138 +531,138 @@ def addTargetAddr( ) -def delTargetAddr(snmpEngine: SnmpEngine, addrName: str): +def delete_target_address(snmpEngine: SnmpEngine, addrName: str): """Delete target address.""" - (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo( + (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cook_target_address_info( snmpEngine, addrName ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpTargetAddrEntry.name + (9,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) -def addTransport( +def add_transport( snmpEngine: SnmpEngine, transportDomain: "tuple[int, ...]", transport: AbstractTransport, ): """Register transport with dispatcher.""" - if snmpEngine.transportDispatcher: - if not transport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): + if snmpEngine.transport_dispatcher: + if not transport.is_compatible_with_dispatcher(snmpEngine.transport_dispatcher): raise error.PySnmpError( - f"Transport {transport!r} is not compatible with dispatcher {snmpEngine.transportDispatcher!r}" + f"Transport {transport!r} is not compatible with dispatcher {snmpEngine.transport_dispatcher!r}" ) else: protoTransportDispatcher = transport.PROTO_TRANSPORT_DISPATCHER if protoTransportDispatcher is not None: - snmpEngine.registerTransportDispatcher(protoTransportDispatcher()) + snmpEngine.register_transport_dispatcher(protoTransportDispatcher()) # here we note that we have created transportDispatcher automatically - snmpEngine.setUserContext(automaticTransportDispatcher=0) + snmpEngine.set_user_context(automaticTransportDispatcher=0) - if snmpEngine.transportDispatcher: - snmpEngine.transportDispatcher.registerTransport(transportDomain, transport) - automaticTransportDispatcher = snmpEngine.getUserContext( + if snmpEngine.transport_dispatcher: + snmpEngine.transport_dispatcher.register_transport(transportDomain, transport) + automaticTransportDispatcher = snmpEngine.get_user_context( "automaticTransportDispatcher" ) if automaticTransportDispatcher is not None: - snmpEngine.setUserContext( + snmpEngine.set_user_context( automaticTransportDispatcher=automaticTransportDispatcher + 1 ) -def getTransport(snmpEngine: SnmpEngine, transportDomain: "tuple[int, ...]"): +def get_transport(snmpEngine: SnmpEngine, transportDomain: "tuple[int, ...]"): """Return transport from dispatcher.""" - if not snmpEngine.transportDispatcher: + if not snmpEngine.transport_dispatcher: return try: - return snmpEngine.transportDispatcher.getTransport(transportDomain) + return snmpEngine.transport_dispatcher.get_transport(transportDomain) except error.PySnmpError: return -def delTransport(snmpEngine: SnmpEngine, transportDomain: "tuple[int, ...]"): +def delete_transport(snmpEngine: SnmpEngine, transportDomain: "tuple[int, ...]"): """Remove transport from dispatcher.""" - if not snmpEngine.transportDispatcher: + if not snmpEngine.transport_dispatcher: return - transport = getTransport(snmpEngine, transportDomain) - snmpEngine.transportDispatcher.unregisterTransport(transportDomain) + transport = get_transport(snmpEngine, transportDomain) + snmpEngine.transport_dispatcher.unregister_transport(transportDomain) # automatically shutdown automatically created transportDispatcher - automaticTransportDispatcher = snmpEngine.getUserContext( + automaticTransportDispatcher = snmpEngine.get_user_context( "automaticTransportDispatcher" ) if automaticTransportDispatcher is not None: automaticTransportDispatcher -= 1 - snmpEngine.setUserContext( + snmpEngine.set_user_context( automaticTransportDispatcher=automaticTransportDispatcher ) if not automaticTransportDispatcher: - snmpEngine.closeDispatcher() - snmpEngine.delUserContext(automaticTransportDispatcher) + snmpEngine.close_dispatcher() + snmpEngine.delete_user_context(automaticTransportDispatcher) return transport -addSocketTransport = addTransport # noqa: N816 -delSocketTransport = delTransport # noqa: N816 +addSocketTransport = add_transport # noqa: N816 +delSocketTransport = delete_transport # noqa: N816 # VACM shortcuts -def __cookVacmContextInfo(snmpEngine, contextName): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - (vacmContextEntry,) = mibBuilder.importSymbols( +def __cook_vacm_context_info(snmpEngine: SnmpEngine, contextName): + mibBuilder = snmpEngine.get_mib_builder() + (vacmContextEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmContextEntry" ) tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) return vacmContextEntry, tblIdx -def addContext(snmpEngine, contextName): +def add_context(snmpEngine: SnmpEngine, contextName): """Setup VACM context.""" - vacmContextEntry, tblIdx = __cookVacmContextInfo(snmpEngine, contextName) + vacmContextEntry, tblIdx = __cook_vacm_context_info(snmpEngine, contextName) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmContextEntry.name + (2,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmContextEntry.name + (1,) + tblIdx, contextName), (vacmContextEntry.name + (2,) + tblIdx, "createAndGo"), **dict(snmpEngine=snmpEngine), ) -def delContext(snmpEngine, contextName): +def delete_context(snmpEngine: SnmpEngine, contextName): """Delete VACM context.""" - vacmContextEntry, tblIdx = __cookVacmContextInfo(snmpEngine, contextName) + vacmContextEntry, tblIdx = __cook_vacm_context_info(snmpEngine, contextName) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmContextEntry.name + (2,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) -def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_vacm_group_info(snmpEngine: SnmpEngine, securityModel, securityName): + mibBuilder = snmpEngine.get_mib_builder() - (vacmSecurityToGroupEntry,) = mibBuilder.importSymbols( + (vacmSecurityToGroupEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupEntry" ) tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, securityName) return vacmSecurityToGroupEntry, tblIdx -def addVacmGroup(snmpEngine, groupName, securityModel, securityName): +def add_vacm_group(snmpEngine: SnmpEngine, groupName, securityModel, securityName): """Setup VACM group.""" - (vacmSecurityToGroupEntry, tblIdx) = __cookVacmGroupInfo( + (vacmSecurityToGroupEntry, tblIdx) = __cook_vacm_group_info( snmpEngine, securityModel, securityName ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmSecurityToGroupEntry.name + (5,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName), @@ -693,23 +671,23 @@ def addVacmGroup(snmpEngine, groupName, securityModel, securityName): ) -def delVacmGroup(snmpEngine, securityModel, securityName): +def delete_vacm_group(snmpEngine: SnmpEngine, securityModel, securityName): """Delete VACM group.""" - vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( + vacmSecurityToGroupEntry, tblIdx = __cook_vacm_group_info( snmpEngine, securityModel, securityName ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmSecurityToGroupEntry.name + (5,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) -def __cookVacmAccessInfo( - snmpEngine, groupName, contextName, securityModel, securityLevel +def __cook_vacm_access_info( + snmpEngine: SnmpEngine, groupName, contextName, securityModel, securityLevel ): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() - (vacmAccessEntry,) = mibBuilder.importSymbols( + (vacmAccessEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessEntry" ) tblIdx = vacmAccessEntry.getInstIdFromIndices( @@ -718,8 +696,8 @@ def __cookVacmAccessInfo( return vacmAccessEntry, tblIdx -def addVacmAccess( - snmpEngine, +def add_vacm_access( + snmpEngine: SnmpEngine, groupName, contextPrefix, securityModel, @@ -730,14 +708,14 @@ def addVacmAccess( notifyView, ): """Setup VACM access.""" - vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + vacmAccessEntry, tblIdx = __cook_vacm_access_info( snmpEngine, groupName, contextPrefix, securityModel, securityLevel ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmAccessEntry.name + (9,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine) ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmAccessEntry.name + (1,) + tblIdx, contextPrefix), (vacmAccessEntry.name + (2,) + tblIdx, securityModel), (vacmAccessEntry.name + (3,) + tblIdx, securityLevel), @@ -750,30 +728,34 @@ def addVacmAccess( ) -def delVacmAccess(snmpEngine, groupName, contextPrefix, securityModel, securityLevel): +def delete_vacm_access( + snmpEngine: SnmpEngine, groupName, contextPrefix, securityModel, securityLevel +): """Delete VACM access.""" - vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + vacmAccessEntry, tblIdx = __cook_vacm_access_info( snmpEngine, groupName, contextPrefix, securityModel, securityLevel ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmAccessEntry.name + (9,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine) ) -def __cookVacmViewInfo(snmpEngine, viewName, subTree): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_vacm_view_info(snmpEngine: SnmpEngine, viewName, subTree): + mibBuilder = snmpEngine.get_mib_builder() - (vacmViewTreeFamilyEntry,) = mibBuilder.importSymbols( + (vacmViewTreeFamilyEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyEntry" ) tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) return vacmViewTreeFamilyEntry, tblIdx -def addVacmView(snmpEngine, viewName, viewType, subTree, subTreeMask): +def add_vacm_view(snmpEngine: SnmpEngine, viewName, viewType, subTree, subTreeMask): """Setup VACM view.""" - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) + vacmViewTreeFamilyEntry, tblIdx = __cook_vacm_view_info( + snmpEngine, viewName, subTree + ) # Allow bitmask specification in form of an OID if rfc1902.OctetString(".").asOctets() in rfc1902.OctetString(subTreeMask): @@ -788,11 +770,11 @@ def addVacmView(snmpEngine, viewName, viewType, subTree, subTreeMask): "".join(str(x) for x in subTreeMask) ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, subTreeMask), @@ -802,10 +784,12 @@ def addVacmView(snmpEngine, viewName, viewType, subTree, subTreeMask): ) -def delVacmView(snmpEngine, viewName, subTree): +def delete_vacm_view(snmpEngine: SnmpEngine, viewName, subTree): """Delete VACM view.""" - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + vacmViewTreeFamilyEntry, tblIdx = __cook_vacm_view_info( + snmpEngine, viewName, subTree + ) + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, "destroy"), **dict(snmpEngine=snmpEngine), ) @@ -814,18 +798,20 @@ def delVacmView(snmpEngine, viewName, subTree): # VACM simplicity wrappers -def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder +def __cook_vacm_user_info( + snmpEngine: SnmpEngine, securityModel, securityName, securityLevel +): + mibBuilder = snmpEngine.get_mib_builder() groupName = "v-%s-%d" % (hash(securityName), securityModel) - (SnmpSecurityLevel,) = mibBuilder.importSymbols( + (SnmpSecurityLevel,) = mibBuilder.importSymbols( # type: ignore "SNMP-FRAMEWORK-MIB", "SnmpSecurityLevel" ) securityLevel = SnmpSecurityLevel(securityLevel) return (groupName, securityLevel, "r" + groupName, "w" + groupName, "n" + groupName) -def addVacmUser( +def add_vacm_user( snmpEngine: SnmpEngine, securityModel: int, securityName: str, @@ -836,12 +822,12 @@ def addVacmUser( contextName=b"", ): """Setup VACM user.""" - (groupName, securityLevel, readView, writeView, notifyView) = __cookVacmUserInfo( + (groupName, securityLevel, readView, writeView, notifyView) = __cook_vacm_user_info( snmpEngine, securityModel, securityName, securityLevel ) - addContext(snmpEngine, contextName) - addVacmGroup(snmpEngine, groupName, securityModel, securityName) - addVacmAccess( + add_context(snmpEngine, contextName) + add_vacm_group(snmpEngine, groupName, securityModel, securityName) + add_vacm_access( snmpEngine, groupName, contextName, @@ -853,15 +839,15 @@ def addVacmUser( notifyView, ) if readSubTree: - addVacmView(snmpEngine, readView, "included", readSubTree, b"") + add_vacm_view(snmpEngine, readView, "included", readSubTree, b"") if writeSubTree: - addVacmView(snmpEngine, writeView, "included", writeSubTree, b"") + add_vacm_view(snmpEngine, writeView, "included", writeSubTree, b"") if notifySubTree: - addVacmView(snmpEngine, notifyView, "included", notifySubTree, b"") + add_vacm_view(snmpEngine, notifyView, "included", notifySubTree, b"") -def delVacmUser( - snmpEngine, +def delete_vacm_user( + snmpEngine: SnmpEngine, securityModel, securityName, securityLevel, @@ -871,29 +857,29 @@ def delVacmUser( contextName=b"", ): """Delete VACM user.""" - (groupName, securityLevel, readView, writeView, notifyView) = __cookVacmUserInfo( + (groupName, securityLevel, readView, writeView, notifyView) = __cook_vacm_user_info( snmpEngine, securityModel, securityName, securityLevel ) - delContext(snmpEngine, contextName) - delVacmGroup(snmpEngine, securityModel, securityName) - delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel) + delete_context(snmpEngine, contextName) + delete_vacm_group(snmpEngine, securityModel, securityName) + delete_vacm_access(snmpEngine, groupName, contextName, securityModel, securityLevel) if readSubTree: - delVacmView(snmpEngine, readView, readSubTree) + delete_vacm_view(snmpEngine, readView, readSubTree) if writeSubTree: - delVacmView(snmpEngine, writeView, writeSubTree) + delete_vacm_view(snmpEngine, writeView, writeSubTree) if notifySubTree: - delVacmView(snmpEngine, notifyView, notifySubTree) + delete_vacm_view(snmpEngine, notifyView, notifySubTree) # Notification target setup -def __cookNotificationTargetInfo( - snmpEngine, notificationName, paramsName, filterSubtree=None +def __cook_notification_target_info( + snmpEngine: SnmpEngine, notificationName, paramsName, filterSubtree=None ): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() - (snmpNotifyEntry,) = mibBuilder.importSymbols( + (snmpNotifyEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-NOTIFICATION-MIB", "snmpNotifyEntry" ) tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) @@ -924,8 +910,8 @@ def __cookNotificationTargetInfo( ) -def addNotificationTarget( - snmpEngine, +def add_notification_target( + snmpEngine: SnmpEngine, notificationName, paramsName, transportTag, @@ -943,26 +929,26 @@ def addNotificationTarget( profileName, snmpNotifyFilterEntry, tblIdx3, - ) = __cookNotificationTargetInfo( + ) = __cook_notification_target_info( snmpEngine, notificationName, paramsName, filterSubtree ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyEntry.name + (5,) + tblIdx1, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType), (snmpNotifyEntry.name + (5,) + tblIdx1, "createAndGo"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName), (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, "createAndGo"), **dict(snmpEngine=snmpEngine), @@ -971,11 +957,11 @@ def addNotificationTarget( if not snmpNotifyFilterEntry: return - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterEntry.name + (5,) + tblIdx3, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType), @@ -984,7 +970,9 @@ def addNotificationTarget( ) -def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): +def delete_notification_target( + snmpEngine: SnmpEngine, notificationName, paramsName, filterSubtree=None +): """Remove notification target.""" ( snmpNotifyEntry, @@ -994,16 +982,16 @@ def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtre profileName, snmpNotifyFilterEntry, tblIdx3, - ) = __cookNotificationTargetInfo( + ) = __cook_notification_target_info( snmpEngine, notificationName, paramsName, filterSubtree ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyEntry.name + (5,) + tblIdx1, "destroy"), **dict(snmpEngine=snmpEngine), ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, "destroy"), **dict(snmpEngine=snmpEngine), ) @@ -1011,25 +999,25 @@ def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtre if not snmpNotifyFilterEntry: return - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (snmpNotifyFilterEntry.name + (5,) + tblIdx3, "destroy"), **dict(snmpEngine=snmpEngine), ) # rfc3415: A.1 -def setInitialVacmParameters(snmpEngine): +def set_initial_vacm_parameters(snmpEngine: SnmpEngine): """Set initial VACM parameters as per SNMP-FRAMEWORK-MIB.""" # rfc3415: A.1.1 --> initial-semi-security-configuration # rfc3415: A.1.2 - addContext(snmpEngine, "") + add_context(snmpEngine, "") # rfc3415: A.1.3 - addVacmGroup(snmpEngine, "initial", 3, "initial") + add_vacm_group(snmpEngine, "initial", 3, "initial") # rfc3415: A.1.4 - addVacmAccess( + add_vacm_access( snmpEngine, "initial", "", @@ -1040,7 +1028,7 @@ def setInitialVacmParameters(snmpEngine): None, "restricted", ) - addVacmAccess( + add_vacm_access( snmpEngine, "initial", "", @@ -1051,7 +1039,7 @@ def setInitialVacmParameters(snmpEngine): "internet", "internet", ) - addVacmAccess( + add_vacm_access( snmpEngine, "initial", "", @@ -1064,9 +1052,15 @@ def setInitialVacmParameters(snmpEngine): ) # rfc3415: A.1.5 (semi-secure) - addVacmView(snmpEngine, "internet", "included", (1, 3, 6, 1), "") - addVacmView(snmpEngine, "restricted", "included", (1, 3, 6, 1, 2, 1, 1), "") - addVacmView(snmpEngine, "restricted", "included", (1, 3, 6, 1, 2, 1, 11), "") - addVacmView(snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 10, 2, 1), "") - addVacmView(snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 11, 2, 1), "") - addVacmView(snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 15, 1, 1), "") + add_vacm_view(snmpEngine, "internet", "included", (1, 3, 6, 1), "") + add_vacm_view(snmpEngine, "restricted", "included", (1, 3, 6, 1, 2, 1, 1), "") + add_vacm_view(snmpEngine, "restricted", "included", (1, 3, 6, 1, 2, 1, 11), "") + add_vacm_view( + snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 10, 2, 1), "" + ) + add_vacm_view( + snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 11, 2, 1), "" + ) + add_vacm_view( + snmpEngine, "restricted", "included", (1, 3, 6, 1, 6, 3, 15, 1, 1), "" + ) diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index 9189717b3..c9b7cd167 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -61,11 +61,11 @@ class SnmpEngine: """ - transportDispatcher: "AbstractTransportDispatcher | None" - msgAndPduDsp: MsgAndPduDispatcher - snmpEngineId: OctetString + transport_dispatcher: "AbstractTransportDispatcher | None" + message_dispatcher: MsgAndPduDispatcher + engine_id: OctetString cache: Dict[str, Any] - securityModels: Dict[int, AbstractSecurityModel] + security_models: Dict[int, AbstractSecurityModel] def __init__( self, @@ -79,15 +79,15 @@ def __init__( self.observer = observer.MetaObserver() if msgAndPduDsp is None: - self.msgAndPduDsp = MsgAndPduDispatcher() + self.message_dispatcher = MsgAndPduDispatcher() else: - self.msgAndPduDsp = msgAndPduDsp + self.message_dispatcher = msgAndPduDsp self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV1MessageProcessingModel(), SnmpV2cMessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV2cMessageProcessingModel(), SnmpV3MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV3MessageProcessingModel(), } - self.securityModels = { + self.security_models = { SnmpV1SecurityModel.SECURITY_MODEL_ID: SnmpV1SecurityModel(), SnmpV2cSecurityModel.SECURITY_MODEL_ID: SnmpV2cSecurityModel(), SnmpUSMSecurityModel.SECURITY_MODEL_ID: SnmpUSMSecurityModel(), @@ -97,27 +97,23 @@ def __init__( rfc3415.Vacm.ACCESS_MODEL_ID: rfc3415.Vacm(), } - self.transportDispatcher = None + self.transport_dispatcher = None - if self.msgAndPduDsp.mibInstrumController is None: + if self.message_dispatcher.mib_instrum_controller is None: raise error.PySnmpError("MIB instrumentation does not yet exist") ( snmpEngineMaxMessageSize, - ) = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + ) = self.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize" ) snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone( maxMessageSize ) - ( - snmpEngineBoots, - ) = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (snmpEngineBoots,) = self.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineBoots" ) snmpEngineBoots.syntax += 1 - ( - origSnmpEngineID, - ) = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (origSnmpEngineID,) = self.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) @@ -187,10 +183,10 @@ def _close(self): This method is intended for unit testing purposes only. It closes the SNMP engine and checks if all associated resources are released. """ - for securityModel in self.securityModels.values(): + for securityModel in self.security_models.values(): securityModel._close() - def openDispatcher(self, timeout: float = 0): + def open_dispatcher(self, timeout: float = 0): """ Open the dispatcher used by SNMP engine. @@ -198,78 +194,82 @@ def openDispatcher(self, timeout: float = 0): messages. It opens the dispatcher and starts processing incoming messages. """ - if self.transportDispatcher: - self.transportDispatcher.runDispatcher(timeout) + if self.transport_dispatcher: + self.transport_dispatcher.run_dispatcher(timeout) - def closeDispatcher(self): + def close_dispatcher(self): """ Close the dispatcher used by SNMP engine. This method is called when SNMP engine is no longer needed. It releases all resources allocated by the engine. """ - if self.transportDispatcher: - self.transportDispatcher.closeDispatcher() - self.unregisterTransportDispatcher() + if self.transport_dispatcher: + self.transport_dispatcher.close_dispatcher() + self.unregister_transport_dispatcher() # Transport dispatcher bindings - def __receiveMessageCbFun( + def __receive_message_callback( self, transportDispatcher: AbstractTransportDispatcher, transportDomain: "tuple[int, ...]", transportAddress: AbstractTransportAddress, wholeMsg, ): - self.msgAndPduDsp.receiveMessage( + self.message_dispatcher.receiveMessage( self, transportDomain, transportAddress, wholeMsg ) - def __receiveTimerTickCbFun(self, timeNow: float): - self.msgAndPduDsp.receiveTimerTick(self, timeNow) + def __receive_timer_tick_callback(self, timeNow: float): + self.message_dispatcher.receiveTimerTick(self, timeNow) for mpHandler in self.messageProcessingSubsystems.values(): mpHandler.receiveTimerTick(self, timeNow) - for smHandler in self.securityModels.values(): + for smHandler in self.security_models.values(): smHandler.receiveTimerTick(self, timeNow) - def registerTransportDispatcher( + def register_transport_dispatcher( self, transportDispatcher: AbstractTransportDispatcher, recvId: "tuple[int, ...] | str | None" = None, ): """Register transport dispatcher.""" if ( - self.transportDispatcher is not None - and self.transportDispatcher is not transportDispatcher + self.transport_dispatcher is not None + and self.transport_dispatcher is not transportDispatcher ): raise error.PySnmpError("Transport dispatcher already registered") - transportDispatcher.registerRecvCbFun(self.__receiveMessageCbFun, recvId) - if self.transportDispatcher is None: - transportDispatcher.registerTimerCbFun(self.__receiveTimerTickCbFun) - self.transportDispatcher = transportDispatcher + transportDispatcher.register_recv_callback( + self.__receive_message_callback, recvId + ) + if self.transport_dispatcher is None: + transportDispatcher.register_timer_callback( + self.__receive_timer_tick_callback + ) + self.transport_dispatcher = transportDispatcher - def unregisterTransportDispatcher(self, recvId: "tuple[int, ...] | None" = None): + def unregister_transport_dispatcher(self, recvId: "tuple[int, ...] | None" = None): """Remove transport dispatcher.""" - if self.transportDispatcher is None: + if self.transport_dispatcher is None: raise error.PySnmpError("Transport dispatcher not registered") - self.transportDispatcher.unregisterRecvCbFun(recvId) - self.transportDispatcher.unregisterTimerCbFun() - self.transportDispatcher = None + self.transport_dispatcher.unregister_recv_callback(recvId) + self.transport_dispatcher.unregister_timer_callback() + self.transport_dispatcher = None - def getMibBuilder(self) -> MibBuilder: + def get_mib_builder(self) -> MibBuilder: """Get MIB builder.""" - return self.msgAndPduDsp.mibInstrumController.mibBuilder + return self.message_dispatcher.mib_instrum_controller.mibBuilder # User app may attach opaque objects to SNMP Engine - def setUserContext(self, **kwargs): + def set_user_context(self, **kwargs): """Attach user context to the SNMP engine.""" self.cache.update({"__%s" % k: kwargs[k] for k in kwargs}) - def getUserContext(self, arg) -> "dict[str, Any] | None": + def get_user_context(self, arg) -> "dict[str, Any] | None": """Get user context.""" return self.cache.get("__%s" % arg) - def delUserContext(self, arg): + def delete_user_context(self, arg): """Delete user context.""" try: del self.cache["__%s" % arg] diff --git a/pysnmp/entity/observer.py b/pysnmp/entity/observer.py index d862d2563..3d2cbb10e 100644 --- a/pysnmp/entity/observer.py +++ b/pysnmp/entity/observer.py @@ -4,8 +4,14 @@ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com> # License: https://www.pysnmp.com/pysnmp/license.html # +from typing import TYPE_CHECKING + + from pysnmp import error +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + class MetaObserver: r"""This is a simple facility for exposing internal SNMP Engine working details to pysnmp applications. @@ -66,7 +72,7 @@ def unregisterObserver(self, cbFun=None): if not self.__observers[execpoint]: del self.__observers[execpoint] - def storeExecutionContext(self, snmpEngine, execpoint, variables): + def storeExecutionContext(self, snmpEngine: "SnmpEngine", execpoint, variables): """Store execution context at specified execution point. Args: @@ -78,7 +84,7 @@ def storeExecutionContext(self, snmpEngine, execpoint, variables): for cbFun in self.__observers[execpoint]: cbFun(snmpEngine, execpoint, variables, self.__contexts[cbFun]) - def clearExecutionContext(self, snmpEngine, *execpoints): + def clearExecutionContext(self, snmpEngine: "SnmpEngine", *execpoints): """Clear execution context at specified execution points. Args: diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py index 0600ab3b0..77b42c37b 100644 --- a/pysnmp/entity/rfc3413/cmdgen.py +++ b/pysnmp/entity/rfc3413/cmdgen.py @@ -30,7 +30,7 @@ def __init__(self, **options): def processResponsePdu( self, - snmpEngine, + snmpEngine: SnmpEngine, messageProcessingModel, securityModel, securityName, @@ -67,7 +67,7 @@ def processResponsePdu( origDiscoveryRetries, ) = self.__pendingReqs.pop(sendPduHandle) - snmpEngine.transportDispatcher.jobFinished(id(self)) + snmpEngine.transport_dispatcher.job_finished(id(self)) # 3.1.3 if statusInformation: @@ -104,7 +104,7 @@ def processResponsePdu( pduVersion = 1 try: - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + sendPduHandle = snmpEngine.message_dispatcher.sendPdu( snmpEngine, origTransportDomain, origTransportAddress, @@ -122,7 +122,7 @@ def processResponsePdu( (origSendRequestHandle, cbFun, cbCtx), ) - snmpEngine.transportDispatcher.jobStarted(id(self)) + snmpEngine.transport_dispatcher.job_started(id(self)) self.__pendingReqs[sendPduHandle] = ( origTransportDomain, @@ -213,14 +213,16 @@ def sendPdu( securityLevel, ) = config.getTargetInfo(snmpEngine, targetName) - if snmpEngine.transportDispatcher is None: + if snmpEngine.transport_dispatcher is None: raise error.PySnmpError("No transport dispatcher available") # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = ( - float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() + float(timeout) + / 100 + / snmpEngine.transport_dispatcher.get_timer_resolution() ) - SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + SnmpEngineID, SnmpAdminString = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-FRAMEWORK-MIB", "SnmpEngineID", "SnmpAdminString" ) @@ -241,7 +243,7 @@ def sendPdu( sendRequestHandle = getNextHandle() # 3.1 - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + sendPduHandle = snmpEngine.message_dispatcher.sendPdu( snmpEngine, transportDomain, transportAddress, @@ -259,7 +261,7 @@ def sendPdu( (sendRequestHandle, cbFun, cbCtx), ) - snmpEngine.transportDispatcher.jobStarted(id(self)) + snmpEngine.transport_dispatcher.job_started(id(self)) self.__pendingReqs[sendPduHandle] = ( transportDomain, @@ -290,7 +292,7 @@ class GetCommandGenerator(CommandGenerator): """SNMP GET command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP GET response.""" cbFun, cbCtx = cbCtx @@ -307,7 +309,7 @@ def processResponseVarBinds( def sendVarBinds( self, - snmpEngine, + snmpEngine: SnmpEngine, targetName, contextEngineId, contextName, @@ -336,7 +338,7 @@ class SetCommandGenerator(CommandGenerator): """SNMP SET command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP SET response.""" cbFun, cbCtx = cbCtx @@ -353,7 +355,7 @@ def processResponseVarBinds( def sendVarBinds( self, - snmpEngine, + snmpEngine: SnmpEngine, targetName, contextEngineId, contextName, @@ -382,7 +384,7 @@ class NextCommandGeneratorSingleRun(CommandGenerator): """Single-run SNMP GETNEXT command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP GETNEXT response.""" targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx @@ -399,7 +401,7 @@ def processResponseVarBinds( def sendVarBinds( self, - snmpEngine, + snmpEngine: SnmpEngine, targetName, contextEngineId, contextName, @@ -428,7 +430,7 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): """SNMP GETNEXT command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP GETNEXT response.""" targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx @@ -467,7 +469,7 @@ class BulkCommandGeneratorSingleRun(CommandGenerator): """Single-run SNMP GETBULK command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP GETBULK response.""" ( @@ -493,7 +495,7 @@ def processResponseVarBinds( def sendVarBinds( self, - snmpEngine, + snmpEngine: SnmpEngine, targetName, contextEngineId, contextName, @@ -536,7 +538,7 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): """Bulk SNMP GET command generator.""" def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx ): """Process SNMP GETBULK response.""" ( diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index 53fb3e338..d864cdeb1 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -44,7 +44,7 @@ class CommandResponderBase: def __init__(self, snmpEngine: SnmpEngine, snmpContext, cbCtx=None): """Create a responder object.""" - snmpEngine.msgAndPduDsp.registerContextEngineId( + snmpEngine.message_dispatcher.registerContextEngineId( snmpContext.contextEngineId, self.SUPPORTED_PDU_TYPES, self.processPdu ) self.snmpContext = snmpContext @@ -55,15 +55,15 @@ def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acCt """Handle incoming SNMP PDU.""" pass - def close(self, snmpEngine): + def close(self, snmpEngine: SnmpEngine): """Unregister responder object.""" - snmpEngine.msgAndPduDsp.unregisterContextEngineId( + snmpEngine.message_dispatcher.unregisterContextEngineId( self.snmpContext.contextEngineId, self.SUPPORTED_PDU_TYPES ) self.snmpContext = self.__pendingReqs = None def sendVarBinds( - self, snmpEngine, stateReference, errorStatus, errorIndex, varBinds + self, snmpEngine: SnmpEngine, stateReference, errorStatus, errorIndex, varBinds ): """Send VarBinds.""" ( @@ -92,7 +92,7 @@ def sendVarBinds( self.sendPdu(snmpEngine, stateReference, PDU) - def sendPdu(self, snmpEngine, stateReference, PDU): + def sendPdu(self, snmpEngine: SnmpEngine, stateReference, PDU): """Send PDU.""" ( messageProcessingModel, @@ -114,7 +114,7 @@ def sendPdu(self, snmpEngine, stateReference, PDU): # 3.2.6 try: - snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine.message_dispatcher.returnResponsePdu( snmpEngine, messageProcessingModel, securityModel, @@ -133,9 +133,7 @@ def sendPdu(self, snmpEngine, stateReference, PDU): debug.logger & debug.FLAG_APP and debug.logger( f"sendPdu: stateReference {stateReference}, statusInformation {sys.exc_info()[1]}" ) - ( - snmpSilentDrops, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpSilentDrops,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "__SNMPv2-MIB", "snmpSilentDrops" ) snmpSilentDrops.syntax += 1 @@ -152,7 +150,7 @@ def releaseStateInformation(self, stateReference): def processPdu( self, - snmpEngine, + snmpEngine: SnmpEngine, messageProcessingModel, securityModel, securityName, @@ -256,7 +254,7 @@ def verifyAccess(cls, viewType, varBind, **context) -> "bool | None": """Verify access rights for a single OID-value pair.""" name, val = varBind - snmpEngine = context["snmpEngine"] + snmpEngine: SnmpEngine = context["snmpEngine"] execCtx = snmpEngine.observer.getExecutionContext( "rfc3412.receiveMessage:request" @@ -299,9 +297,7 @@ def verifyAccess(cls, viewType, varBind, **context) -> "bool | None": raise smi_error.GenError(name=name, idx=context.get("idx")) elif errorIndication == errind.noSuchContext: - ( - snmpUnknownContexts, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpUnknownContexts,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-TARGET-MIB", "snmpUnknownContexts" ) snmpUnknownContexts.syntax += 1 @@ -336,7 +332,9 @@ class GetCommandResponder(CommandResponderBase): SUPPORTED_PDU_TYPES = (rfc1905.GetRequestPDU.tagSet,) # rfc1905: 4.2.1 - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU): + def handleMgmtOperation( + self, snmpEngine: SnmpEngine, stateReference, contextName, PDU + ): """Handle incoming SNMP GetRequest-PDU.""" # rfc1905: 4.2.1.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars @@ -356,7 +354,9 @@ class NextCommandResponder(CommandResponderBase): SUPPORTED_PDU_TYPES = (rfc1905.GetNextRequestPDU.tagSet,) # rfc1905: 4.2.2 - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU): + def handleMgmtOperation( + self, snmpEngine: SnmpEngine, stateReference, contextName, PDU + ): """Handle incoming SNMP GetNextRequest-PDU.""" # rfc1905: 4.2.2.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars @@ -387,7 +387,9 @@ class BulkCommandResponder(CommandResponderBase): maxVarBinds = 64 # rfc1905: 4.2.3 - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU): + def handleMgmtOperation( + self, snmpEngine: SnmpEngine, stateReference, contextName, PDU + ): """Handle incoming SNMP GetBulkRequest-PDU.""" nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) if nonRepeaters < 0: @@ -441,7 +443,9 @@ class SetCommandResponder(CommandResponderBase): SUPPORTED_PDU_TYPES = (rfc1905.SetRequestPDU.tagSet,) # rfc1905: 4.2.5 - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU): + def handleMgmtOperation( + self, snmpEngine: SnmpEngine, stateReference, contextName, PDU + ): """Handle incoming SNMP SetRequest-PDU.""" mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py index 66125a85b..c09e09243 100644 --- a/pysnmp/entity/rfc3413/config.py +++ b/pysnmp/entity/rfc3413/config.py @@ -14,16 +14,16 @@ def getTargetAddr(snmpEngine: SnmpEngine, snmpTargetAddrName): """Return transport endpoint information for a given target.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpTargetAddrEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-TARGET-MIB", "snmpTargetAddrEntry" ) - cache: "dict[str, Any] | None" = snmpEngine.getUserContext("getTargetAddr") + cache: "dict[str, Any] | None" = snmpEngine.get_user_context("getTargetAddr") if cache is None: cache = {"id": -1} - snmpEngine.setUserContext(getTargetAddr=cache) + snmpEngine.set_user_context(getTargetAddr=cache) if cache["id"] != snmpTargetAddrEntry.branchVersionId: cache["nameToTargetMap"] = {} @@ -71,9 +71,9 @@ def getTargetAddr(snmpEngine: SnmpEngine, snmpTargetAddrName): except NoSuchInstanceError: raise SmiError("Target %s not configured to LCD" % snmpTargetAddrName) - if snmpEngine.transportDispatcher is None: + if snmpEngine.transport_dispatcher is None: raise PySnmpError("TransportDispatcher not set") - transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain) + transport = snmpEngine.transport_dispatcher.get_transport(snmpTargetAddrTDomain) if ( snmpTargetAddrTDomain[: len(config.SNMP_UDP_DOMAIN)] @@ -81,22 +81,22 @@ def getTargetAddr(snmpEngine: SnmpEngine, snmpTargetAddrName): ): ( SnmpUDPAddress, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + ) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMPv2-TM", "SnmpUDPAddress" ) addr = transport.ADDRESS_TYPE( # type: ignore SnmpUDPAddress(snmpTargetAddrTAddress) - ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress)) + ).set_local_address(SnmpUDPAddress(snmpSourceAddrTAddress)) elif ( snmpTargetAddrTDomain[: len(config.SNMP_UDP6_DOMAIN)] == config.SNMP_UDP6_DOMAIN ): - (TransportAddressIPv6,) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (TransportAddressIPv6,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "TRANSPORT-ADDRESS-MIB", "TransportAddressIPv6" ) addr = transport.ADDRESS_TYPE( # type: ignore TransportAddressIPv6(snmpTargetAddrTAddress) - ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress)) + ).set_local_address(TransportAddressIPv6(snmpSourceAddrTAddress)) nameToTargetMap[snmpTargetAddrName] = ( snmpTargetAddrTDomain, @@ -113,16 +113,16 @@ def getTargetAddr(snmpEngine: SnmpEngine, snmpTargetAddrName): def getTargetParams(snmpEngine: SnmpEngine, paramsName): """Return security parameters for a given target.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpTargetParamsEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-TARGET-MIB", "snmpTargetParamsEntry" ) - cache: "dict[str, Any] | None" = snmpEngine.getUserContext("getTargetParams") + cache: "dict[str, Any] | None" = snmpEngine.get_user_context("getTargetParams") if cache is None: cache = {"id": -1} - snmpEngine.setUserContext(getTargetParams=cache) + snmpEngine.set_user_context(getTargetParams=cache) if cache["id"] != snmpTargetParamsEntry.branchVersionId: cache["nameToParamsMap"] = {} @@ -205,16 +205,16 @@ def getTargetInfo(snmpEngine: SnmpEngine, snmpTargetAddrName): def getNotificationInfo(snmpEngine: SnmpEngine, notificationTarget): """Return notification tag and type for a given target.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpNotifyEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-NOTIFICATION-MIB", "snmpNotifyEntry" ) - cache: "dict[str, Any] | None" = snmpEngine.getUserContext("getNotificationInfo") + cache: "dict[str, Any] | None" = snmpEngine.get_user_context("getNotificationInfo") if cache is None: cache = {"id": -1} - snmpEngine.setUserContext(getNotificationInfo=cache) + snmpEngine.set_user_context(getNotificationInfo=cache) if cache["id"] != snmpNotifyEntry.branchVersionId: cache["targetToNotifyMap"] = {} # type: ignore @@ -244,16 +244,16 @@ def getNotificationInfo(snmpEngine: SnmpEngine, notificationTarget): def getTargetNames(snmpEngine: SnmpEngine, tag): """Return a list of target names associated with a given tag.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpTargetAddrEntry,) = mibBuilder.importSymbols( # type: ignore "SNMP-TARGET-MIB", "snmpTargetAddrEntry" ) - cache: "dict[str, Any] | None" = snmpEngine.getUserContext("getTargetNames") + cache: "dict[str, Any] | None" = snmpEngine.get_user_context("getTargetNames") if cache is None: cache = {"id": -1} - snmpEngine.setUserContext(getTargetNames=cache) + snmpEngine.set_user_context(getTargetNames=cache) if cache["id"] == snmpTargetAddrEntry.branchVersionId: tagToTargetsMap = cache["tagToTargetsMap"] diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py index 86d951389..58190b429 100644 --- a/pysnmp/entity/rfc3413/context.py +++ b/pysnmp/entity/rfc3413/context.py @@ -15,9 +15,7 @@ class SnmpContext: def __init__(self, snmpEngine: SnmpEngine, contextEngineId=None): """Create a context object.""" - ( - snmpEngineId, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (snmpEngineId,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) if contextEngineId is None: @@ -29,7 +27,7 @@ def __init__(self, snmpEngine: SnmpEngine, contextEngineId=None): f'SnmpContext: contextEngineId "{self.contextEngineId!r}"' ) self.contextNames = { - b"": snmpEngine.msgAndPduDsp.mibInstrumController # Default name + b"": snmpEngine.message_dispatcher.mib_instrum_controller # Default name } def registerContextName(self, contextName, mibInstrum=None): diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index c1ac07dff..de43ccc8d 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -69,7 +69,7 @@ def processResponsePdu( origDiscoveryRetries, ) = self.__pendingReqs.pop(sendPduHandle) - snmpEngine.transportDispatcher.jobFinished(id(self)) + snmpEngine.transport_dispatcher.job_finished(id(self)) if statusInformation: debug.logger & debug.FLAG_APP and debug.logger( @@ -102,7 +102,7 @@ def processResponsePdu( timeoutInTicks = ( float(origTimeout) / 100 - / snmpEngine.transportDispatcher.getTimerResolution() + / snmpEngine.transport_dispatcher.get_timer_resolution() ) # User-side API assumes SMIv2 @@ -115,7 +115,7 @@ def processResponsePdu( # 3.3.6a try: - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + sendPduHandle = snmpEngine.message_dispatcher.sendPdu( snmpEngine, origTransportDomain, origTransportAddress, @@ -148,7 +148,7 @@ def processResponsePdu( ) return - snmpEngine.transportDispatcher.jobStarted(id(self)) + snmpEngine.transport_dispatcher.job_started(id(self)) debug.logger & debug.FLAG_APP and debug.logger( "processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d" @@ -188,7 +188,7 @@ def processResponsePdu( def sendPdu( self, - snmpEngine, + snmpEngine: SnmpEngine, targetName, contextEngineId, contextName, @@ -226,13 +226,13 @@ def sendPdu( timeoutInTicks = ( float(timeout) / 100 - / snmpEngine.transportDispatcher.getTimerResolution() + / snmpEngine.transport_dispatcher.get_timer_resolution() ) sendRequestHandle = getNextHandle() # 3.3.6a - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + sendPduHandle = snmpEngine.message_dispatcher.sendPdu( snmpEngine, transportDomain, transportAddress, @@ -270,9 +270,9 @@ def sendPdu( 0, 0, ) - snmpEngine.transportDispatcher.jobStarted(id(self)) + snmpEngine.transport_dispatcher.job_started(id(self)) else: - snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine.message_dispatcher.sendPdu( snmpEngine, transportDomain, transportAddress, @@ -294,7 +294,7 @@ def sendPdu( return sendRequestHandle def processResponseVarBinds( - self, snmpEngine, sendRequestHandle, errorIndication, pdu, cbCtx + self, snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, pdu, cbCtx ): """Process SNMP PDU response.""" notificationHandle, cbFun, cbCtx = cbCtx @@ -367,7 +367,7 @@ def sendVarBinds( ) ) - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() if contextName: (__SnmpAdminString,) = mibBuilder.importSymbols( diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index d57ab8b21..498ee60d7 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -8,6 +8,7 @@ from pysnmp import debug +from pysnmp.entity.engine import SnmpEngine from pysnmp.proto import error, rfc3411 from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant from pysnmp.proto.proxy import rfc2576 @@ -23,9 +24,9 @@ class NotificationReceiver: v2c.InformRequestPDU.tagSet, ) - def __init__(self, snmpEngine, cbFun, cbCtx=None): + def __init__(self, snmpEngine: SnmpEngine, cbFun, cbCtx=None): """Creates a Notification receiver instance.""" - snmpEngine.msgAndPduDsp.registerContextEngineId( + snmpEngine.message_dispatcher.registerContextEngineId( b"", self.SUPPORTED_PDU_TYPES, self.processPdu # '' is a wildcard ) @@ -40,14 +41,16 @@ def storeSnmpTrapCommunity(snmpEngine, execpoint, variables, cbCtx): storeSnmpTrapCommunity, "rfc2576.processIncomingMsg" ) - def close(self, snmpEngine): + def close(self, snmpEngine: SnmpEngine): """Unregisters a Notification receiver instance.""" - snmpEngine.msgAndPduDsp.unregisterContextEngineId(b"", self.SUPPORTED_PDU_TYPES) + snmpEngine.message_dispatcher.unregisterContextEngineId( + b"", self.SUPPORTED_PDU_TYPES + ) self.__cbFun = self.__cbCtx = None def processPdu( self, - snmpEngine, + snmpEngine: SnmpEngine, messageProcessingModel, securityModel, securityName, @@ -98,7 +101,7 @@ def processPdu( # 3.4.3 try: - snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine.message_dispatcher.returnResponsePdu( snmpEngine, messageProcessingModel, securityModel, @@ -117,9 +120,7 @@ def processPdu( debug.logger & debug.FLAG_APP and debug.logger( f"processPdu: stateReference {stateReference}, statusInformation {sys.exc_info()[1]}" ) - ( - snmpSilentDrops, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpSilentDrops,) = snmpEngine.get_mib_builder().importSymbols( "__SNMPv2-MIB", "snmpSilentDrops" ) snmpSilentDrops.syntax += 1 diff --git a/pysnmp/hlapi/transport.py b/pysnmp/hlapi/transport.py index 7e6d55d67..b6de566b6 100644 --- a/pysnmp/hlapi/transport.py +++ b/pysnmp/hlapi/transport.py @@ -18,7 +18,7 @@ class AbstractTransportTarget: retries: int timeout: float transport: "AbstractTransport | None" - transportAddr: Tuple[str, int] + transport_address: Tuple[str, int] TRANSPORT_DOMAIN = None PROTO_TRANSPORT = AbstractTransport @@ -35,7 +35,7 @@ def __init__( self.iface = None self.transport = None - if not hasattr(self, "transportAddr"): + if not hasattr(self, "transport_address"): raise Exception( f"Please call .create() to construct {self.__class__.__name__} object" ) @@ -57,23 +57,23 @@ async def create(cls, address: Tuple[str, int], *args, **kwargs): """ self = cls.__new__(cls) transportAddr = address - self.transportAddr = await self._resolveAddr(transportAddr) + self.transport_address = await self._resolve_address(transportAddr) self.__init__(*args, **kwargs) return self def __repr__(self): return "{}({!r}, timeout={!r}, retries={!r}, tagList={!r})".format( self.__class__.__name__, - self.transportAddr, + self.transport_address, self.timeout, self.retries, self.tagList, ) - def getTransportInfo(self): - return self.TRANSPORT_DOMAIN, self.transportAddr + def get_transport_info(self): + return self.TRANSPORT_DOMAIN, self.transport_address - def setLocalAddress(self, iface): + def set_local_address(self, iface): """Set source address. Parameters @@ -90,22 +90,22 @@ def setLocalAddress(self, iface): self.iface = iface return self - def openClientMode(self): - self.transport = self.PROTO_TRANSPORT().openClientMode(self.iface) + def open_client_mode(self): + self.transport = self.PROTO_TRANSPORT().open_client_mode(self.iface) return self.transport - def verifyDispatcherCompatibility(self, snmpEngine: SnmpEngine): + def verify_dispatcher_compatibility(self, snmpEngine: SnmpEngine): if ( - snmpEngine.transportDispatcher is None - or not self.PROTO_TRANSPORT.isCompatibleWithDispatcher( - snmpEngine.transportDispatcher + snmpEngine.transport_dispatcher is None + or not self.PROTO_TRANSPORT.is_compatible_with_dispatcher( + snmpEngine.transport_dispatcher ) ): raise error.PySnmpError( "Transport {!r} is not compatible with dispatcher {!r}".format( - self.PROTO_TRANSPORT, snmpEngine.transportDispatcher + self.PROTO_TRANSPORT, snmpEngine.transport_dispatcher ) ) - async def _resolveAddr(self, transportAddr: Tuple) -> Tuple[str, int]: + async def _resolve_address(self, transportAddr: Tuple) -> Tuple[str, int]: raise NotImplementedError() diff --git a/pysnmp/hlapi/v1arch/asyncio/slim.py b/pysnmp/hlapi/v1arch/asyncio/slim.py index 99d2f5ff5..90194b1dd 100644 --- a/pysnmp/hlapi/v1arch/asyncio/slim.py +++ b/pysnmp/hlapi/v1arch/asyncio/slim.py @@ -55,7 +55,7 @@ def __init__(self, version: int = 2): def close(self): """Closes the wrapper to release its resources.""" - self.snmpDispatcher.transportDispatcher.closeDispatcher() + self.snmpDispatcher.transportDispatcher.close_dispatcher() def __enter__(self): """Returns the wrapper object.""" diff --git a/pysnmp/hlapi/v1arch/asyncio/transport.py b/pysnmp/hlapi/v1arch/asyncio/transport.py index 8ddc743b0..64a9b1677 100644 --- a/pysnmp/hlapi/v1arch/asyncio/transport.py +++ b/pysnmp/hlapi/v1arch/asyncio/transport.py @@ -55,7 +55,7 @@ class instance. TRANSPORT_DOMAIN: Tuple[int, ...] = udp.DOMAIN_NAME PROTO_TRANSPORT = udp.UdpAsyncioTransport - async def _resolveAddr(self, transportAddr: Tuple) -> Tuple[str, int]: + async def _resolve_address(self, transportAddr: Tuple) -> Tuple[str, int]: try: loop = asyncio.get_event_loop() return ( @@ -124,7 +124,7 @@ class instance. TRANSPORT_DOMAIN: Tuple[int, ...] = udp6.DOMAIN_NAME PROTO_TRANSPORT = udp6.Udp6AsyncioTransport - async def _resolveAddr(self, transportAddr: Tuple) -> Tuple[str, int]: + async def _resolve_address(self, transportAddr: Tuple) -> Tuple[str, int]: try: loop = asyncio.get_event_loop() return ( diff --git a/pysnmp/hlapi/v1arch/dispatch.py b/pysnmp/hlapi/v1arch/dispatch.py index 8094aae20..bd6ac71a4 100644 --- a/pysnmp/hlapi/v1arch/dispatch.py +++ b/pysnmp/hlapi/v1arch/dispatch.py @@ -8,6 +8,9 @@ from pyasn1.codec.ber import decoder, encoder from pysnmp import debug +from pysnmp.carrier.base import AbstractTransportDispatcher +from pysnmp.entity.engine import SnmpEngine +from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp.proto import api from pysnmp.proto import error from pysnmp.proto.api import verdec @@ -34,7 +37,7 @@ class AbstractSnmpDispatcher: PROTO_DISPATCHER = None - def __init__(self, transportDispatcher=None): + def __init__(self, transportDispatcher: AbstractTransportDispatcher = None): if transportDispatcher: self.transportDispatcher = transportDispatcher @@ -46,8 +49,8 @@ def __init__(self, transportDispatcher=None): self._pendingReqs = {} - self.transportDispatcher.registerRecvCbFun(self._recvCb) - self.transportDispatcher.registerTimerCbFun(self._timerCb) + self.transportDispatcher.register_recv_callback(self._recvCb) + self.transportDispatcher.register_timer_callback(self._timerCb) self.cache = {} @@ -57,8 +60,8 @@ def __repr__(self): ) def close(self): - self.transportDispatcher.unregisterRecvCbFun() - self.transportDispatcher.unregisterTimerCbFun() + self.transportDispatcher.unregister_recv_callback() + self.transportDispatcher.unregister_timer_callback() if self._automaticDispatcher: self.transportDispatcher.close() @@ -71,14 +74,21 @@ def close(self): self._pendingReqs.clear() - def sendPdu(self, authData, transportTarget, reqPdu, cbFun=None, cbCtx=None): + def sendPdu( + self, + authData, + transportTarget: AbstractTransportTarget, + reqPdu, + cbFun=None, + cbCtx=None, + ): if ( self._automaticDispatcher and transportTarget.TRANSPORT_DOMAIN not in self._configuredTransports ): - self.transportDispatcher.registerTransport( + self.transportDispatcher.register_transport( transportTarget.TRANSPORT_DOMAIN, - transportTarget.PROTO_TRANSPORT().openClientMode(), + transportTarget.PROTO_TRANSPORT().open_client_mode(), ) self._configuredTransports.add(transportTarget.TRANSPORT_DOMAIN) @@ -102,8 +112,10 @@ def sendPdu(self, authData, transportTarget, reqPdu, cbFun=None, cbCtx=None): retries=0, ) - self.transportDispatcher.sendMessage( - outgoingMsg, transportTarget.TRANSPORT_DOMAIN, transportTarget.transportAddr + self.transportDispatcher.send_message( + outgoingMsg, + transportTarget.TRANSPORT_DOMAIN, + transportTarget.transport_address, ) if reqPdu.__class__ is getattr( @@ -111,13 +123,15 @@ def sendPdu(self, authData, transportTarget, reqPdu, cbFun=None, cbCtx=None): ) or reqPdu.__class__ is getattr(pMod, "TrapPDU", None): return requestId - self.transportDispatcher.jobStarted(id(self)) + self.transportDispatcher.job_started(id(self)) return requestId - def _recvCb(self, snmpEngine, transportDomain, transportAddress, wholeMsg): + def _recvCb( + self, snmpEngine: SnmpEngine, transportDomain, transportAddress, wholeMsg + ): try: - mpModel = verdec.decodeMessageVersion(wholeMsg) + mpModel = verdec.decode_message_version(wholeMsg) except error.ProtocolError: return # n.b the whole buffer gets dropped @@ -140,7 +154,7 @@ def _recvCb(self, snmpEngine, transportDomain, transportAddress, wholeMsg): except KeyError: continue - self.transportDispatcher.jobFinished(id(self)) + self.transportDispatcher.job_finished(id(self)) cbFun = stateInfo["cbFun"] cbCtx = stateInfo["cbCtx"] @@ -156,7 +170,7 @@ def _timerCb(self, timeNow): continue retries = stateInfo["retries"] - transportTarget = stateInfo["transportTarget"] + transportTarget: AbstractTransportTarget = stateInfo["transportTarget"] if retries == transportTarget.retries: cbFun = stateInfo["cbFun"] @@ -171,7 +185,7 @@ def _timerCb(self, timeNow): None, cbCtx, ) - self.transportDispatcher.jobFinished(id(self)) + self.transportDispatcher.job_finished(id(self)) continue stateInfo["retries"] += 1 @@ -179,8 +193,8 @@ def _timerCb(self, timeNow): outgoingMsg = stateInfo["outgoingMsg"] - self.transportDispatcher.sendMessage( + self.transportDispatcher.send_message( outgoingMsg, transportTarget.TRANSPORT_DOMAIN, - transportTarget.transportAddr, + transportTarget.transport_address, ) diff --git a/pysnmp/hlapi/v3arch/asyncio/lcd.py b/pysnmp/hlapi/v3arch/asyncio/lcd.py index 2cfe30645..c3d6814d5 100644 --- a/pysnmp/hlapi/v3arch/asyncio/lcd.py +++ b/pysnmp/hlapi/v3arch/asyncio/lcd.py @@ -17,12 +17,12 @@ class AbstractLcdConfigurator: nextID = nextid.Integer(0xFFFFFFFF) cacheKeys = [] - def _getCache(self, snmpEngine): + def _getCache(self, snmpEngine: SnmpEngine): cacheId = self.__class__.__name__ - cache = snmpEngine.getUserContext(cacheId) + cache = snmpEngine.get_user_context(cacheId) if cache is None: cache = {x: {} for x in self.cacheKeys} - snmpEngine.setUserContext(**{cacheId: cache}) + snmpEngine.set_user_context(**{cacheId: cache}) return cache def configure(self, snmpEngine, *args, **kwargs): @@ -38,13 +38,18 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ["auth", "parm", "tran", "addr"] def configure( - self, snmpEngine, authData, transportTarget, contextName=b"", **options + self, + snmpEngine: SnmpEngine, + authData, + transportTarget: AbstractTransportTarget, + contextName=b"", + **options, ): """Configure command generator targets on the SNMP engine.""" cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache["auth"]: - config.addV1System( + config.add_v1_system( snmpEngine, authData.communityIndex, authData.communityName, @@ -60,7 +65,7 @@ def configure( add_user = True elif self._usm_auth_changed(cache["auth"][authDataKey], authData): - config.delV3User( + config.delete_v3_user( snmpEngine, authData.userName, authData.securityEngineId ) add_user = True @@ -69,7 +74,7 @@ def configure( add_user = False if add_user: - config.addV3User( + config.add_v3_user( snmpEngine, authData.userName, authData.authProtocol, @@ -91,7 +96,7 @@ def configure( cache["parm"][paramsKey] = paramsName, useCount + 1 else: paramsName = "p%s" % self.nextID() - config.addTargetParams( + config.add_target_parameters( snmpEngine, paramsName, authData.securityName, @@ -102,19 +107,21 @@ def configure( if transportTarget.TRANSPORT_DOMAIN in cache["tran"]: transport, useCount = cache["tran"][transportTarget.TRANSPORT_DOMAIN] - transportTarget.verifyDispatcherCompatibility(snmpEngine) + transportTarget.verify_dispatcher_compatibility(snmpEngine) cache["tran"][transportTarget.TRANSPORT_DOMAIN] = transport, useCount + 1 - elif config.getTransport(snmpEngine, transportTarget.TRANSPORT_DOMAIN): - transportTarget.verifyDispatcherCompatibility(snmpEngine) + elif config.get_transport(snmpEngine, transportTarget.TRANSPORT_DOMAIN): + transportTarget.verify_dispatcher_compatibility(snmpEngine) else: - transport = transportTarget.openClientMode() - config.addTransport(snmpEngine, transportTarget.TRANSPORT_DOMAIN, transport) + transport = transportTarget.open_client_mode() + config.add_transport( + snmpEngine, transportTarget.TRANSPORT_DOMAIN, transport + ) cache["tran"][transportTarget.TRANSPORT_DOMAIN] = transport, 1 transportKey = ( paramsName, transportTarget.TRANSPORT_DOMAIN, - transportTarget.transportAddr, + transportTarget.transport_address, transportTarget.timeout, transportTarget.retries, transportTarget.tagList, @@ -126,11 +133,11 @@ def configure( cache["addr"][transportKey] = addrName, useCount + 1 else: addrName = "a%s" % self.nextID() - config.addTargetAddr( + config.add_target_address( snmpEngine, addrName, transportTarget.TRANSPORT_DOMAIN, - transportTarget.transportAddr, + transportTarget.transport_address, paramsName, transportTarget.timeout * 100, transportTarget.retries, @@ -140,7 +147,9 @@ def configure( return addrName, paramsName - def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): + def unconfigure( + self, snmpEngine: SnmpEngine, authData=None, contextName=b"", **options + ): """Remove command generator targets from the SNMP engine.""" cache = self._getCache(snmpEngine) if authData: @@ -163,9 +172,9 @@ def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): authDataX = cache["auth"][authDataKey] del cache["auth"][authDataKey] if isinstance(authDataX, CommunityData): - config.delV1System(snmpEngine, authDataX.communityIndex) + config.delete_v1_system(snmpEngine, authDataX.communityIndex) elif isinstance(authDataX, UsmUserData): - config.delV3User( + config.delete_v3_user( snmpEngine, authDataX.userName, authDataX.securityEngineId ) else: @@ -183,7 +192,7 @@ def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): cache["parm"][paramsKey] = paramsName, useCount else: del cache["parm"][paramsKey] - config.delTargetParams(snmpEngine, paramsName) + config.delete_target_parameters(snmpEngine, paramsName) paramsNames.add(paramsName) else: raise error.PySnmpError(f"Unknown target {paramsKey}") @@ -196,7 +205,7 @@ def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): if useCount: cache["addr"][addrKey] = addrName, useCount else: - config.delTargetAddr(snmpEngine, addrName) + config.delete_target_address(snmpEngine, addrName) del cache["addr"][addrKey] addrNames.add(addrKey) @@ -206,7 +215,7 @@ def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): useCount -= 1 cache["tran"][addrKey[1]] = transport, useCount else: - config.delTransport(snmpEngine, addrKey[1]) + config.delete_transport(snmpEngine, addrKey[1]) transport.closeTransport() del cache["tran"][addrKey[1]] @@ -246,7 +255,7 @@ def configure( # Create matching transport tags if not given by user. Not good! if not transportTarget.tagList: transportTarget.tagList = str( - hash((authData.securityName, transportTarget.transportAddr)) + hash((authData.securityName, transportTarget.transport_address)) ) if isinstance(authData, CommunityData) and not authData.tag: authData.tag = transportTarget.tagList.split()[0] @@ -264,7 +273,7 @@ def configure( cache["name"][notifyNameKey] = notifyName, paramsName, useCount + 1 else: notifyName = "n%s" % self.nextID() - config.addNotificationTarget( + config.add_notification_target( snmpEngine, notifyName, paramsName, tag, notifyType ) cache["name"][notifyNameKey] = notifyName, paramsName, 1 @@ -279,7 +288,7 @@ def configure( cache["auth"][authDataKey] = authDataX, subTree, useCount + 1 else: subTree = (1, 3, 6) - config.addVacmUser( + config.add_vacm_user( snmpEngine, authData.securityModel, authData.securityName, @@ -293,7 +302,9 @@ def configure( return notifyName - def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): + def unconfigure( + self, snmpEngine: SnmpEngine, authData=None, contextName=b"", **options + ): """Remove notification targets from the SNMP engine.""" cache = self._getCache(snmpEngine) if authData: @@ -323,7 +334,7 @@ def unconfigure(self, snmpEngine, authData=None, contextName=b"", **options): if useCount: cache["name"][notifyNameKey] = notifyName, paramsName, useCount else: - config.delNotificationTarget(snmpEngine, notifyName, paramsName) + config.delete_notification_target(snmpEngine, notifyName, paramsName) del cache["name"][notifyNameKey] for authDataKey in authDataKeys: diff --git a/pysnmp/hlapi/v3arch/asyncio/ntforg.py b/pysnmp/hlapi/v3arch/asyncio/ntforg.py index a9c7fc1a3..8325c17a1 100644 --- a/pysnmp/hlapi/v3arch/asyncio/ntforg.py +++ b/pysnmp/hlapi/v3arch/asyncio/ntforg.py @@ -133,7 +133,7 @@ async def sendNotification( """ def __cbFun( - snmpEngine, + snmpEngine: SnmpEngine, sendRequestHandle, errorIndication, errorStatus, diff --git a/pysnmp/hlapi/v3arch/asyncio/transport.py b/pysnmp/hlapi/v3arch/asyncio/transport.py index 594001eb9..407ee0411 100644 --- a/pysnmp/hlapi/v3arch/asyncio/transport.py +++ b/pysnmp/hlapi/v3arch/asyncio/transport.py @@ -52,7 +52,7 @@ class instance. TRANSPORT_DOMAIN: Tuple[int, ...] = udp.DOMAIN_NAME PROTO_TRANSPORT = udp.UdpAsyncioTransport - async def _resolveAddr(self, transportAddr: Tuple) -> Tuple[str, int]: + async def _resolve_address(self, transportAddr: Tuple) -> Tuple[str, int]: try: loop = asyncio.get_event_loop() return ( @@ -121,7 +121,7 @@ class instance. TRANSPORT_DOMAIN: Tuple[int, ...] = udp6.DOMAIN_NAME PROTO_TRANSPORT = udp6.Udp6AsyncioTransport - async def _resolveAddr(self, transportAddr: Tuple) -> Tuple[str, int]: + async def _resolve_address(self, transportAddr: Tuple) -> Tuple[str, int]: try: loop = asyncio.get_event_loop() return ( diff --git a/pysnmp/proto/acmod/rfc3415.py b/pysnmp/proto/acmod/rfc3415.py index f0435c3d5..3f3d22920 100644 --- a/pysnmp/proto/acmod/rfc3415.py +++ b/pysnmp/proto/acmod/rfc3415.py @@ -4,10 +4,15 @@ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com> # License: https://www.pysnmp.com/pysnmp/license.html # +from typing import TYPE_CHECKING + from pysnmp import debug from pysnmp.proto import errind, error from pysnmp.smi.error import NoSuchInstanceError +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + # 3.2 class Vacm: @@ -139,7 +144,7 @@ def _getFamilyViewName( def isAccessAllowed( self, - snmpEngine, + snmpEngine: "SnmpEngine", securityModel, securityName, securityLevel, @@ -164,7 +169,6 @@ def isAccessAllowed( Raises: StatusInformation: If access is denied. """ - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController debug.logger & debug.FLAG_ACL and debug.logger( "isAccessAllowed: securityModel %s, securityName %s, " @@ -182,7 +186,7 @@ def isAccessAllowed( # Rebuild contextName map if changed - (vacmContextName,) = mibInstrumController.mibBuilder.importSymbols( + (vacmContextName,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmContextName" ) @@ -208,12 +212,12 @@ def isAccessAllowed( # Rebuild groupName map if changed - (vacmGroupName,) = mibInstrumController.mibBuilder.importSymbols( + (vacmGroupName,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName" ) if self._groupNameBranchId != vacmGroupName.branchVersionId: - (vacmSecurityToGroupEntry,) = mibInstrumController.mibBuilder.importSymbols( + (vacmSecurityToGroupEntry,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupEntry" ) @@ -247,7 +251,7 @@ def isAccessAllowed( # Rebuild access map if changed - (vacmAccessStatus,) = mibInstrumController.mibBuilder.importSymbols( + (vacmAccessStatus,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStatus" ) @@ -261,7 +265,7 @@ def isAccessAllowed( vacmAccessReadViewName, vacmAccessWriteViewName, vacmAccessNotifyViewName, - ) = mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessEntry", "vacmAccessContextPrefix", @@ -326,7 +330,7 @@ def isAccessAllowed( # Rebuild family subtree map if changed - (vacmViewTreeFamilyViewName,) = mibInstrumController.mibBuilder.importSymbols( + (vacmViewTreeFamilyViewName,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyViewName" ) @@ -335,7 +339,7 @@ def isAccessAllowed( vacmViewTreeFamilySubtree, vacmViewTreeFamilyMask, vacmViewTreeFamilyType, - ) = mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilySubtree", "vacmViewTreeFamilyMask", diff --git a/pysnmp/proto/acmod/void.py b/pysnmp/proto/acmod/void.py index 5a96fdc68..065227114 100644 --- a/pysnmp/proto/acmod/void.py +++ b/pysnmp/proto/acmod/void.py @@ -4,9 +4,15 @@ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com> # License: https://www.pysnmp.com/pysnmp/license.html # +from typing import TYPE_CHECKING + + from pysnmp import debug from pysnmp.proto import errind, error +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + # rfc3415 3.2 # noinspection PyUnusedLocal @@ -17,7 +23,7 @@ class Vacm: def isAccessAllowed( self, - snmpEngine, + snmpEngine: "SnmpEngine", securityModel, securityName, securityLevel, diff --git a/pysnmp/proto/api/__init__.py b/pysnmp/proto/api/__init__.py index f7fdc0832..3c1e71cf5 100644 --- a/pysnmp/proto/api/__init__.py +++ b/pysnmp/proto/api/__init__.py @@ -25,4 +25,4 @@ SNMP_VERSION_2C = 1 PROTOCOL_MODULES = {SNMP_VERSION_1: v1, SNMP_VERSION_2C: v2c} -decodeMessageVersion = verdec.decodeMessageVersion # noqa: N816 +decodeMessageVersion = verdec.decode_message_version # noqa: N816 diff --git a/pysnmp/proto/api/verdec.py b/pysnmp/proto/api/verdec.py index bc89d8be3..8ec161096 100644 --- a/pysnmp/proto/api/verdec.py +++ b/pysnmp/proto/api/verdec.py @@ -10,7 +10,7 @@ from pysnmp.proto.error import ProtocolError -def decodeMessageVersion(wholeMsg): +def decode_message_version(wholeMsg): """Decode SNMP version from the message.""" try: seq, wholeMsg = decoder.decode( diff --git a/pysnmp/proto/mpmod/base.py b/pysnmp/proto/mpmod/base.py index 56eb964c3..018a33ab0 100644 --- a/pysnmp/proto/mpmod/base.py +++ b/pysnmp/proto/mpmod/base.py @@ -4,9 +4,14 @@ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com> # License: https://www.pysnmp.com/pysnmp/license.html # +from typing import TYPE_CHECKING + from pysnmp.proto import error from pysnmp.proto.mpmod import cache +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + class AbstractMessageProcessingModel: """Create a message processing model object.""" @@ -20,7 +25,7 @@ def __init__(self): def prepareOutgoingMessage( self, - snmpEngine, + snmpEngine: "SnmpEngine", transportDomain, transportAddress, messageProcessingModel, @@ -39,7 +44,7 @@ def prepareOutgoingMessage( def prepareResponseMessage( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, securityModel, securityName, @@ -56,7 +61,7 @@ def prepareResponseMessage( raise error.ProtocolError("method not implemented") def prepareDataElements( - self, snmpEngine, transportDomain, transportAddress, wholeMsg + self, snmpEngine: "SnmpEngine", transportDomain, transportAddress, wholeMsg ): """Prepare SNMP message data elements.""" raise error.ProtocolError("method not implemented") @@ -68,6 +73,6 @@ def releaseStateInformation(self, sendPduHandle): except error.ProtocolError: pass # XXX maybe these should all follow some scheme? - def receiveTimerTick(self, snmpEngine, timeNow): + def receiveTimerTick(self, snmpEngine: "SnmpEngine", timeNow): """Process a timer tick.""" self._cache.expireCaches() diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py index 3c4d42989..00eccc9ff 100644 --- a/pysnmp/proto/mpmod/rfc2576.py +++ b/pysnmp/proto/mpmod/rfc2576.py @@ -5,6 +5,8 @@ # License: https://www.pysnmp.com/pysnmp/license.html # import sys +from typing import TYPE_CHECKING + from pyasn1.codec.ber import decoder, eoo from pyasn1.type import univ @@ -13,6 +15,8 @@ from pysnmp.proto.api import v1, v2c from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine # Since I have not found a detailed reference to v1MP/v2cMP # inner workings, the following has been patterned from v3MP. Most @@ -28,7 +32,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.1 def prepareOutgoingMessage( self, - snmpEngine, + snmpEngine: "SnmpEngine", transportDomain, transportAddress, messageProcessingModel, @@ -43,7 +47,7 @@ def prepareOutgoingMessage( sendPduHandle, ): """Prepare SNMP message for dispatch.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpEngineId,) = mibBuilder.importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" @@ -91,8 +95,8 @@ def prepareOutgoingMessage( globalData = (msg,) k = int(securityModel) - if k in snmpEngine.securityModels: - smHandler = snmpEngine.securityModels[k] + if k in snmpEngine.security_models: + smHandler = snmpEngine.security_models[k] else: raise error.StatusInformation( errorIndication=errind.unsupportedSecurityModel @@ -171,7 +175,7 @@ def prepareOutgoingMessage( # rfc3412: 7.1 def prepareResponseMessage( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, securityModel, securityName, @@ -185,7 +189,7 @@ def prepareResponseMessage( statusInformation, ): """Prepare SNMP message for response.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (snmpEngineId,) = mibBuilder.importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" @@ -256,8 +260,8 @@ def prepareResponseMessage( globalData = (msg,) k = int(securityModel) - if k in snmpEngine.securityModels: - smHandler = snmpEngine.securityModels[k] + if k in snmpEngine.security_models: + smHandler = snmpEngine.security_models[k] else: raise error.StatusInformation( errorIndication=errind.unsupportedSecurityModel @@ -309,10 +313,10 @@ def prepareResponseMessage( # rfc3412: 7.2.1 def prepareDataElements( - self, snmpEngine, transportDomain, transportAddress, wholeMsg + self, snmpEngine: "SnmpEngine", transportDomain, transportAddress, wholeMsg ): """Prepare SNMP message data elements.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() # rfc3412: 7.2.2 msg, restOfWholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec) @@ -342,7 +346,7 @@ def prepareDataElements( try: try: - smHandler = snmpEngine.securityModels[securityModel] + smHandler = snmpEngine.security_models[securityModel] except KeyError: raise error.StatusInformation( diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py index 90f196f56..d34bdffba 100644 --- a/pysnmp/proto/mpmod/rfc3412.py +++ b/pysnmp/proto/mpmod/rfc3412.py @@ -143,7 +143,7 @@ def getPeerEngineInfo(self, transportDomain, transportAddress): # 7.1.1a def prepareOutgoingMessage( self, - snmpEngine, + snmpEngine: SnmpEngine, transportDomain, transportAddress, messageProcessingModel, @@ -158,9 +158,7 @@ def prepareOutgoingMessage( sendPduHandle, ): """Prepare SNMP message for dispatch.""" - ( - snmpEngineID, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpEngineID,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) snmpEngineID = snmpEngineID.syntax @@ -234,9 +232,7 @@ def prepareOutgoingMessage( 0, msgID, verifyConstraints=False, matchTags=False, matchConstraints=False ) - ( - snmpEngineMaxMessageSize, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpEngineMaxMessageSize,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize" ) @@ -280,8 +276,8 @@ def prepareOutgoingMessage( f"prepareOutgoingMessage: {msg.prettyPrint()}" ) - if securityModel in snmpEngine.securityModels: - smHandler = snmpEngine.securityModels[securityModel] + if securityModel in snmpEngine.security_models: + smHandler = snmpEngine.security_models[securityModel] else: raise error.StatusInformation( errorIndication=errind.unsupportedSecurityModel @@ -379,9 +375,7 @@ def prepareResponseMessage( statusInformation, ): """Prepare SNMP message for response.""" - ( - snmpEngineID, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (snmpEngineID,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) snmpEngineID = snmpEngineID.syntax @@ -504,9 +498,7 @@ def prepareResponseMessage( 0, msgID, verifyConstraints=False, matchTags=False, matchConstraints=False ) - ( - snmpEngineMaxMessageSize, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpEngineMaxMessageSize,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize" ) @@ -555,8 +547,8 @@ def prepareResponseMessage( f"prepareResponseMessage: {msg.prettyPrint()}" ) - if securityModel in snmpEngine.securityModels: - smHandler = snmpEngine.securityModels[securityModel] + if securityModel in snmpEngine.security_models: + smHandler = snmpEngine.security_models[securityModel] else: raise error.StatusInformation( errorIndication=errind.unsupportedSecurityModel @@ -621,7 +613,7 @@ def prepareResponseMessage( # 7.2.1 def prepareDataElements( - self, snmpEngine, transportDomain, transportAddress, wholeMsg + self, snmpEngine: SnmpEngine, transportDomain, transportAddress, wholeMsg ): """Prepare SNMP message data elements.""" # 7.2.2 @@ -650,10 +642,8 @@ def prepareDataElements( ) # 7.2.4 - if securityModel not in snmpEngine.securityModels: - ( - snmpUnknownSecurityModels, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + if securityModel not in snmpEngine.security_models: + (snmpUnknownSecurityModels,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-MPD-MIB", "snmpUnknownSecurityModels" ) snmpUnknownSecurityModels.syntax += 1 @@ -669,9 +659,7 @@ def prepareDataElements( elif (msgFlags & 0x03) == 0x03: securityLevel = 3 else: - ( - snmpInvalidMsgs, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpInvalidMsgs,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-MPD-MIB", "snmpInvalidMsgs" ) snmpInvalidMsgs.syntax += 1 @@ -683,7 +671,7 @@ def prepareDataElements( reportableFlag = 0 # 7.2.6 - smHandler = snmpEngine.securityModels[securityModel] + smHandler = snmpEngine.security_models[securityModel] try: ( securityEngineId, @@ -767,7 +755,7 @@ def prepareDataElements( # 7.2.6a3 try: - snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine.message_dispatcher.returnResponsePdu( snmpEngine, 3, securityModel, @@ -814,7 +802,7 @@ def prepareDataElements( expireAt = int( self.__expirationTimer - + 300 / snmpEngine.transportDispatcher.getTimerResolution() + + 300 / snmpEngine.transport_dispatcher.get_timer_resolution() ) if expireAt not in self.__engineIdCacheExpQueue: self.__engineIdCacheExpQueue[expireAt] = [] @@ -826,9 +814,7 @@ def prepareDataElements( ) ) - ( - snmpEngineID, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpEngineID,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) snmpEngineID = snmpEngineID.syntax @@ -1093,7 +1079,7 @@ def __expireEnginesInfo(self): del self.__engineIdCacheExpQueue[self.__expirationTimer] self.__expirationTimer += 1 - def receiveTimerTick(self, snmpEngine, timeNow): + def receiveTimerTick(self, snmpEngine: SnmpEngine, timeNow): """Process periodic timer tick.""" self.__expireEnginesInfo() AbstractMessageProcessingModel.receiveTimerTick(self, snmpEngine, timeNow) diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py index 1f6cdd5f3..68076ec0e 100644 --- a/pysnmp/proto/rfc3412.py +++ b/pysnmp/proto/rfc3412.py @@ -5,6 +5,7 @@ # License: https://www.pysnmp.com/pysnmp/license.html # import sys +from typing import TYPE_CHECKING from pyasn1.error import PyAsn1Error @@ -14,6 +15,9 @@ from pysnmp.proto.api import verdec # XXX from pysnmp.smi import builder, instrum +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + class MsgAndPduDispatcher: r"""SNMP engine PDU & message dispatcher. @@ -22,20 +26,20 @@ class MsgAndPduDispatcher: applications and serialized messages with transport level. """ - mibInstrumController: instrum.MibInstrumController + mib_instrum_controller: instrum.MibInstrumController def __init__( self, mibInstrumController: "instrum.MibInstrumController | None" = None ): """Create a dispatcher object.""" if mibInstrumController is None: - self.mibInstrumController = instrum.MibInstrumController( + self.mib_instrum_controller = instrum.MibInstrumController( builder.MibBuilder() ) else: - self.mibInstrumController = mibInstrumController + self.mib_instrum_controller = mibInstrumController - self.mibInstrumController.mibBuilder.loadModules( + self.mib_instrum_controller.mibBuilder.loadModules( "SNMPv2-MIB", "SNMP-MPD-MIB", "SNMP-COMMUNITY-MIB", @@ -91,7 +95,7 @@ def unregisterContextEngineId(self, contextEngineId, pduTypes): # 4.3.4 if contextEngineId is None: # Default to local snmpEngineId - (contextEngineId,) = self.mibInstrumController.mibBuilder.importSymbols( + (contextEngineId,) = self.mib_instrum_controller.mibBuilder.importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" # type: ignore ) @@ -119,7 +123,7 @@ def getRegisteredApp(self, contextEngineId, pduType): def sendPdu( self, - snmpEngine, + snmpEngine: "SnmpEngine", transportDomain, transportAddress, messageProcessingModel, @@ -156,7 +160,7 @@ def sendPdu( sendPduHandle, messageProcessingModel=messageProcessingModel, sendPduHandle=sendPduHandle, - timeout=timeout + snmpEngine.transportDispatcher.getTimerTicks(), + timeout=timeout + snmpEngine.transport_dispatcher.get_timer_ticks(), cbFun=cbFun, cbCtx=cbCtx, ) @@ -164,8 +168,8 @@ def sendPdu( debug.logger & debug.FLAG_DSP and debug.logger( "sendPdu: current time %d ticks, one tick is %s seconds" % ( - snmpEngine.transportDispatcher.getTimerTicks(), - snmpEngine.transportDispatcher.getTimerResolution(), + snmpEngine.transport_dispatcher.get_timer_ticks(), + snmpEngine.transport_dispatcher.get_timer_resolution(), ) ) @@ -208,7 +212,7 @@ def sendPdu( raise # 4.1.1.6 - if snmpEngine.transportDispatcher is None: + if snmpEngine.transport_dispatcher is None: if expectResponse: self.__cache.pop(sendPduHandle) @@ -232,7 +236,7 @@ def sendPdu( ) try: - snmpEngine.transportDispatcher.sendMessage( + snmpEngine.transport_dispatcher.send_message( outgoingMessage, transportDomain, transportAddress ) except PySnmpError: @@ -262,7 +266,7 @@ def sendPdu( # 4.1.2.1 def returnResponsePdu( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, securityModel, securityName, @@ -321,14 +325,14 @@ def returnResponsePdu( # Handle oversized messages XXX transport constrains? ( snmpEngineMaxMessageSize, - ) = self.mibInstrumController.mibBuilder.importSymbols( + ) = self.mib_instrum_controller.mibBuilder.importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize" # type: ignore ) if ( snmpEngineMaxMessageSize.syntax and len(outgoingMessage) > snmpEngineMaxMessageSize.syntax ): - (snmpSilentDrops,) = self.mibInstrumController.mibBuilder.importSymbols("__SNMPv2-MIB", "snmpSilentDrops") # type: ignore + (snmpSilentDrops,) = self.mib_instrum_controller.mibBuilder.importSymbols("__SNMPv2-MIB", "snmpSilentDrops") # type: ignore snmpSilentDrops.syntax += 1 raise error.StatusInformation(errorIndication=errind.tooBig) @@ -350,7 +354,7 @@ def returnResponsePdu( ) # 4.1.2.4 - snmpEngine.transportDispatcher.sendMessage( + snmpEngine.transport_dispatcher.send_message( outgoingMessage, transportDomain, transportAddress ) @@ -359,10 +363,12 @@ def returnResponsePdu( ) # 4.2.1 - def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg): + def receiveMessage( + self, snmpEngine: "SnmpEngine", transportDomain, transportAddress, wholeMsg + ): """Message dispatcher -- de-serialize message into PDU.""" # 4.2.1.1 - (snmpInPkts,) = self.mibInstrumController.mibBuilder.importSymbols( # type: ignore + (snmpInPkts,) = self.mib_instrum_controller.mibBuilder.importSymbols( # type: ignore "__SNMPv2-MIB", "snmpInPkts" ) snmpInPkts.syntax += 1 @@ -370,10 +376,12 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg # 4.2.1.2 try: restOfWholeMsg = b"" # XXX fix decoder non-recursive return - msgVersion = verdec.decodeMessageVersion(wholeMsg) + msgVersion = verdec.decode_message_version(wholeMsg) except error.ProtocolError: - (snmpInASNParseErrs,) = self.mibInstrumController.mibBuilder.importSymbols( + ( + snmpInASNParseErrs, + ) = self.mib_instrum_controller.mibBuilder.importSymbols( "__SNMPv2-MIB", "snmpInASNParseErrs" # type: ignore ) snmpInASNParseErrs.syntax += 1 @@ -391,7 +399,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg ] except KeyError: - (snmpInBadVersions,) = self.mibInstrumController.mibBuilder.importSymbols("__SNMPv2-MIB", "snmpInBadVersions") # type: ignore + (snmpInBadVersions,) = self.mib_instrum_controller.mibBuilder.importSymbols("__SNMPv2-MIB", "snmpInBadVersions") # type: ignore snmpInBadVersions.syntax += 1 return restOfWholeMsg @@ -442,9 +450,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg debug.logger & debug.FLAG_MP and debug.logger( f"receiveMessage: {sys.exc_info()[1]}" ) - ( - snmpInASNParseErrs, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpInASNParseErrs,) = snmpEngine.get_mib_builder().importSymbols( "__SNMPv2-MIB", "snmpInASNParseErrs" ) snmpInASNParseErrs.syntax += 1 @@ -470,7 +476,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg # 4.2.2.1.2.a ( snmpUnknownPDUHandlers, - ) = self.mibInstrumController.mibBuilder.importSymbols( + ) = self.mib_instrum_controller.mibBuilder.importSymbols( "__SNMP-MPD-MIB", "snmpUnknownPDUHandlers" # type: ignore ) snmpUnknownPDUHandlers.syntax += 1 @@ -507,7 +513,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg statusInformation, ) - snmpEngine.transportDispatcher.sendMessage( + snmpEngine.transport_dispatcher.send_message( outgoingMessage, destTransportDomain, destTransportAddress ) @@ -587,7 +593,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg if cachedParams is None: ( snmpUnknownPDUHandlers, - ) = self.mibInstrumController.mibBuilder.importSymbols( + ) = self.mib_instrum_controller.mibBuilder.importSymbols( "__SNMP-MPD-MIB", "snmpUnknownPDUHandlers" # type: ignore ) snmpUnknownPDUHandlers.syntax += 1 @@ -646,7 +652,7 @@ def receiveMessage(self, snmpEngine, transportDomain, transportAddress, wholeMsg return restOfWholeMsg def releaseStateInformation( - self, snmpEngine, sendPduHandle, messageProcessingModel + self, snmpEngine: "SnmpEngine", sendPduHandle, messageProcessingModel ): """Release state information.""" k = int(messageProcessingModel) @@ -660,9 +666,9 @@ def releaseStateInformation( # noinspection PyUnusedLocal def __expireRequest( - self, cacheKey, cachedParams, snmpEngine, statusInformation=None + self, cacheKey, cachedParams, snmpEngine: "SnmpEngine", statusInformation=None ): - timeNow = snmpEngine.transportDispatcher.getTimerTicks() + timeNow = snmpEngine.transport_dispatcher.get_timer_ticks() timeoutAt = cachedParams["timeout"] if statusInformation is None and timeNow < timeoutAt: @@ -703,6 +709,6 @@ def __expireRequest( return True # noinspection PyUnusedLocal - def receiveTimerTick(self, snmpEngine, timeNow): + def receiveTimerTick(self, snmpEngine: "SnmpEngine", timeNow): """Process cache timeouts.""" self.__cache.expire(self.__expireRequest, snmpEngine) diff --git a/pysnmp/proto/secmod/base.py b/pysnmp/proto/secmod/base.py index d7cef4816..b72af9ea0 100644 --- a/pysnmp/proto/secmod/base.py +++ b/pysnmp/proto/secmod/base.py @@ -4,10 +4,17 @@ # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com> # License: https://www.pysnmp.com/pysnmp/license.html # + +from typing import TYPE_CHECKING + + from pysnmp.proto import error from pysnmp.proto.errind import ErrorIndication from pysnmp.proto.secmod import cache +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + class AbstractSecurityModel: """Abstract security model class.""" @@ -21,7 +28,7 @@ def __init__(self): def processIncomingMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, maxMessageSize, securityParameters, @@ -35,7 +42,7 @@ def processIncomingMsg( def generateRequestMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -50,7 +57,7 @@ def generateRequestMsg( def generateResponseMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -69,7 +76,7 @@ def releaseStateInformation(self, stateReference): """Release state information.""" self._cache.pop(stateReference) - def receiveTimerTick(self, snmpEngine, timeNow): + def receiveTimerTick(self, snmpEngine: "SnmpEngine", timeNow): """Process a timer tick.""" pass diff --git a/pysnmp/proto/secmod/eso/priv/aesbase.py b/pysnmp/proto/secmod/eso/priv/aesbase.py index ae9bdbc2b..69b825279 100644 --- a/pysnmp/proto/secmod/eso/priv/aesbase.py +++ b/pysnmp/proto/secmod/eso/priv/aesbase.py @@ -21,7 +21,7 @@ class AbstractAesBlumenthal(aes.Aes): KEY_SIZE = 0 # 3.1.2.1 - def localizeKey(self, authProtocol, privKey, snmpEngineID) -> bytes: + def localize_key(self, authProtocol, privKey, snmpEngineID) -> bytes: """AES key localization algorithm. This algorithm is used to localize an AES key to an authoritative @@ -81,7 +81,7 @@ class AbstractAesReeder(aes.Aes): KEY_SIZE = 0 # 2.1 of https://tools.itef.org/pdf/draft_bluementhal-aes-usm-04.txt - def localizeKey(self, authProtocol, privKey, snmpEngineID) -> bytes: + def localize_key(self, authProtocol, privKey, snmpEngineID) -> bytes: """AES key localization algorithm. This algorithm is used to localize an AES key to an authoritative diff --git a/pysnmp/proto/secmod/eso/priv/des3.py b/pysnmp/proto/secmod/eso/priv/des3.py index 0944582de..c0d409cac 100644 --- a/pysnmp/proto/secmod/eso/priv/des3.py +++ b/pysnmp/proto/secmod/eso/priv/des3.py @@ -38,7 +38,7 @@ class Des3(base.AbstractEncryptionService): KEY_SIZE = 32 local_int = random.randrange(0, 0xFFFFFFFF) - def hashPassphrase(self, authProtocol, privKey) -> bytes: + def hash_passphrase(self, authProtocol, privKey) -> bytes: """Hash a passphrase. This method hashes a passphrase using the authentication protocol. @@ -66,7 +66,7 @@ def hashPassphrase(self, authProtocol, privKey) -> bytes: return localkey.hashPassphrase(privKey, hashAlgo) # 2.1 - def localizeKey(self, authProtocol, privKey, snmpEngineID) -> bytes: + def localize_key(self, authProtocol, privKey, snmpEngineID) -> bytes: """3-DES key localization algorithm. This algorithm is used to localize a 3-DES key to an authoritative @@ -147,7 +147,7 @@ def __getDecryptionKey(privKey, salt): ) # 5.1.1.2 - def encryptData(self, encryptKey, privParameters, dataToEncrypt): + def encrypt_data(self, encryptKey, privParameters, dataToEncrypt): """Encrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.encryptionError) @@ -175,7 +175,7 @@ def encryptData(self, encryptKey, privParameters, dataToEncrypt): return univ.OctetString(ciphertext), privParameters # 5.1.1.3 - def decryptData(self, decryptKey, privParameters, encryptedData): + def decrypt_data(self, decryptKey, privParameters, encryptedData): """Decrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.decryptionError) diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py index 7ffdb3587..9da3e57e9 100644 --- a/pysnmp/proto/secmod/rfc2576.py +++ b/pysnmp/proto/secmod/rfc2576.py @@ -5,6 +5,8 @@ # License: https://www.pysnmp.com/pysnmp/license.html # import sys +from typing import TYPE_CHECKING + from pyasn1.codec.ber import encoder from pyasn1.error import PyAsn1Error @@ -14,6 +16,9 @@ from pysnmp.proto.secmod import base from pysnmp.smi.error import NoSuchInstanceError +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + class SnmpV1SecurityModel(base.AbstractSecurityModel): """Create SNMPv1 security model.""" @@ -42,16 +47,16 @@ def _close(self): """ pass - def _sec2com(self, snmpEngine, securityName, contextEngineId, contextName): - ( - snmpTargetParamsSecurityName, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + def _sec2com( + self, snmpEngine: "SnmpEngine", securityName, contextEngineId, contextName + ): + (snmpTargetParamsSecurityName,) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "snmpTargetParamsSecurityName" ) if self.__paramsBranchId != snmpTargetParamsSecurityName.branchVersionId: ( snmpTargetParamsSecurityModel, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel" ) @@ -93,9 +98,7 @@ def _sec2com(self, snmpEngine, securityName, contextEngineId, contextName): # invalidate next map as it include this one self.__securityBranchId = -1 - ( - snmpCommunityName, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpCommunityName,) = snmpEngine.get_mib_builder().importSymbols( "SNMP-COMMUNITY-MIB", "snmpCommunityName" ) if self.__securityBranchId != snmpCommunityName.branchVersionId: @@ -103,7 +106,7 @@ def _sec2com(self, snmpEngine, securityName, contextEngineId, contextName): snmpCommunitySecurityName, snmpCommunityContextEngineId, snmpCommunityContextName, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName", "snmpCommunityContextEngineID", @@ -162,10 +165,8 @@ def _sec2com(self, snmpEngine, securityName, contextEngineId, contextName): except KeyError: raise error.StatusInformation(errorIndication=errind.unknownCommunityName) - def _com2sec(self, snmpEngine, communityName, transportInformation): - ( - snmpTargetAddrTAddress, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + def _com2sec(self, snmpEngine: "SnmpEngine", communityName, transportInformation): + (snmpTargetAddrTAddress,) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "snmpTargetAddrTAddress" ) if self.__transportBranchId != snmpTargetAddrTAddress.branchVersionId: @@ -173,7 +174,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): SnmpTagValue, snmpTargetAddrTDomain, snmpTargetAddrTagList, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetAddrTDomain", @@ -204,9 +205,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): targetAddrTDomain = tuple(targetAddrTDomain) if targetAddrTDomain[: len(udp.SNMP_UDP_DOMAIN)] == udp.SNMP_UDP_DOMAIN: - ( - SnmpUDPAddress, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (SnmpUDPAddress,) = snmpEngine.get_mib_builder().importSymbols( "SNMPv2-TM", "SnmpUDPAddress" ) targetAddrTAddress = tuple(SnmpUDPAddress(targetAddrTAddress)) @@ -216,7 +215,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): ): ( TransportAddressIPv6, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "TRANSPORT-ADDRESS-MIB", "TransportAddressIPv6" ) targetAddrTAddress = tuple(TransportAddressIPv6(targetAddrTAddress)) @@ -256,16 +255,14 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): ) ) - ( - snmpTargetParamsSecurityName, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpTargetParamsSecurityName,) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "snmpTargetParamsSecurityName" ) if self.__paramsBranchId != snmpTargetParamsSecurityName.branchVersionId: ( snmpTargetParamsSecurityModel, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel" ) @@ -313,9 +310,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): ) ) - ( - snmpCommunityName, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpCommunityName,) = snmpEngine.get_mib_builder().importSymbols( "SNMP-COMMUNITY-MIB", "snmpCommunityName" ) if self.__communityBranchId != snmpCommunityName.branchVersionId: @@ -324,7 +319,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): snmpCommunityContextEngineId, snmpCommunityContextName, snmpCommunityTransportTag, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + ) = snmpEngine.get_mib_builder().importSymbols( "SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName", "snmpCommunityContextEngineID", @@ -443,7 +438,7 @@ def _com2sec(self, snmpEngine, communityName, transportInformation): def generateRequestMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -495,7 +490,7 @@ def generateRequestMsg( def generateResponseMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -545,7 +540,7 @@ def generateResponseMsg( def processIncomingMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, maxMessageSize, securityParameters, @@ -577,9 +572,7 @@ def processIncomingMsg( ) except error.StatusInformation: - ( - snmpInBadCommunityNames, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpInBadCommunityNames,) = snmpEngine.get_mib_builder().importSymbols( "__SNMPv2-MIB", "snmpInBadCommunityNames" ) snmpInBadCommunityNames.syntax += 1 @@ -587,9 +580,7 @@ def processIncomingMsg( errorIndication=errind.unknownCommunityName, communityName=communityName ) - ( - snmpEngineID, - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + (snmpEngineID,) = snmpEngine.get_mib_builder().importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) diff --git a/pysnmp/proto/secmod/rfc3414/auth/base.py b/pysnmp/proto/secmod/rfc3414/auth/base.py index 6bc6efd60..173d21263 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/base.py +++ b/pysnmp/proto/secmod/rfc3414/auth/base.py @@ -12,25 +12,25 @@ class AbstractAuthenticationService: SERVICE_ID = None - def hashPassphrase(self, authKey): + def hash_passphrase(self, authKey): """Hash authentication key.""" raise error.ProtocolError(errind.noAuthentication) - def localizeKey(self, authKey, snmpEngineID): + def localize_key(self, authKey, snmpEngineID): """Localize authentication key.""" raise error.ProtocolError(errind.noAuthentication) @property - def digestLength(self): + def digest_length(self): """Return length of the digest produced by this service.""" raise error.ProtocolError(errind.noAuthentication) # 7.2.4.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): + def authenticate_outgoing_message(self, authKey, wholeMsg): """Authenticate outgoing message.""" raise error.ProtocolError(errind.noAuthentication) # 7.2.4.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + def authenticate_incoming_message(self, authKey, authParameters, wholeMsg): """Authenticate incoming message.""" raise error.ProtocolError(errind.noAuthentication) diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py index 75cd966e0..42f6e90fc 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py +++ b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py @@ -28,21 +28,21 @@ class HmacMd5(base.AbstractAuthenticationService): IPAD = [0x36] * 64 OPAD = [0x5C] * 64 - def hashPassphrase(self, authKey): + def hash_passphrase(self, authKey): """Hash a passphrase.""" return localkey.hashPassphraseMD5(authKey) - def localizeKey(self, authKey, snmpEngineID): + def localize_key(self, authKey, snmpEngineID): """Localize a key.""" return localkey.localizeKeyMD5(authKey, snmpEngineID) @property - def digestLength(self): + def digest_length(self): """Return digest length.""" return 12 # 6.3.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): + def authenticate_outgoing_message(self, authKey, wholeMsg): """Authenticate outgoing message.""" # Here we expect calling secmod to indicate where the digest # should be in the substrate. Also, it pre-sets digest placeholder @@ -82,7 +82,7 @@ def authenticateOutgoingMsg(self, authKey, wholeMsg): return wholeHead + mac + wholeTail # 6.3.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + def authenticate_incoming_message(self, authKey, authParameters, wholeMsg): """Authenticate incoming message.""" # 6.3.2.1 & 2 if len(authParameters) != 12: diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py index 546951498..a88236ac4 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py +++ b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py @@ -28,21 +28,21 @@ class HmacSha(base.AbstractAuthenticationService): IPAD = [0x36] * 64 OPAD = [0x5C] * 64 - def hashPassphrase(self, authKey) -> univ.OctetString: + def hash_passphrase(self, authKey) -> univ.OctetString: """Hash a passphrase.""" return localkey.hashPassphraseSHA(authKey) - def localizeKey(self, authKey, snmpEngineID) -> univ.OctetString: + def localize_key(self, authKey, snmpEngineID) -> univ.OctetString: """Localize a key.""" return localkey.localizeKeySHA(authKey, snmpEngineID) @property - def digestLength(self): + def digest_length(self): """Return digest length.""" return 12 # 7.3.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): + def authenticate_outgoing_message(self, authKey, wholeMsg): """Authenticate outgoing message.""" # 7.3.1.1 # Here we expect calling secmod to indicate where the digest @@ -79,7 +79,7 @@ def authenticateOutgoingMsg(self, authKey, wholeMsg): return wholeHead + mac + wholeTail # 7.3.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + def authenticate_incoming_message(self, authKey, authParameters, wholeMsg): """Authenticate incoming message.""" # 7.3.2.1 & 2 if len(authParameters) != 12: diff --git a/pysnmp/proto/secmod/rfc3414/auth/noauth.py b/pysnmp/proto/secmod/rfc3414/auth/noauth.py index f9f4b759c..a81e7fbb4 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/noauth.py +++ b/pysnmp/proto/secmod/rfc3414/auth/noauth.py @@ -17,19 +17,19 @@ class NoAuth(base.AbstractAuthenticationService): SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol - def hashPassphrase(self, authKey): + def hash_passphrase(self, authKey): """Hash a passphrase.""" return - def localizeKey(self, authKey, snmpEngineID): + def localize_key(self, authKey, snmpEngineID): """Localize a key.""" return # 7.2.4.2 - def authenticateOutgoingMsg(self, authKey, wholeMsg): + def authenticate_outgoing_message(self, authKey, wholeMsg): """Authenticate outgoing message.""" raise error.StatusInformation(errorIndication=errind.noAuthentication) - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + def authenticate_incoming_message(self, authKey, authParameters, wholeMsg): """Authenticate incoming message.""" raise error.StatusInformation(errorIndication=errind.noAuthentication) diff --git a/pysnmp/proto/secmod/rfc3414/priv/base.py b/pysnmp/proto/secmod/rfc3414/priv/base.py index bd7b75900..7e54db91f 100644 --- a/pysnmp/proto/secmod/rfc3414/priv/base.py +++ b/pysnmp/proto/secmod/rfc3414/priv/base.py @@ -13,18 +13,18 @@ class AbstractEncryptionService: SERVICE_ID = None KEY_SIZE = 0 - def hashPassphrase(self, authProtocol, privKey): + def hash_passphrase(self, authProtocol, privKey): """Hash authentication key.""" raise error.ProtocolError("no encryption") - def localizeKey(self, authProtocol, privKey, snmpEngineID): + def localize_key(self, authProtocol, privKey, snmpEngineID): """Localize privacy key.""" raise error.ProtocolError("no encryption") - def encryptData(self, encryptKey, privParameters, dataToEncrypt): + def encrypt_data(self, encryptKey, privParameters, dataToEncrypt): """Encrypt data.""" raise error.ProtocolError("no encryption") - def decryptData(self, decryptKey, privParameters, encryptedData): + def decrypt_data(self, decryptKey, privParameters, encryptedData): """Decrypt data.""" raise error.ProtocolError("no encryption") diff --git a/pysnmp/proto/secmod/rfc3414/priv/des.py b/pysnmp/proto/secmod/rfc3414/priv/des.py index d9b46e2d9..9e3f07dc1 100644 --- a/pysnmp/proto/secmod/rfc3414/priv/des.py +++ b/pysnmp/proto/secmod/rfc3414/priv/des.py @@ -36,7 +36,7 @@ class Des(base.AbstractEncryptionService): local_int = random.randrange(0, 0xFFFFFFFF) - def hashPassphrase(self, authProtocol, privKey) -> univ.OctetString: + def hash_passphrase(self, authProtocol, privKey) -> univ.OctetString: """Hash a passphrase. This method hashes a passphrase using the authentication protocol. @@ -63,7 +63,7 @@ def hashPassphrase(self, authProtocol, privKey) -> univ.OctetString: raise error.ProtocolError(f"Unknown auth protocol {authProtocol}") return localkey.hashPassphrase(privKey, hashAlgo) - def localizeKey(self, authProtocol, privKey, snmpEngineID) -> bytes: + def localize_key(self, authProtocol, privKey, snmpEngineID) -> bytes: """Localize privacy key. This method localizes privacy key using the authentication protocol @@ -134,7 +134,7 @@ def __getDecryptionKey(privKey, salt): ) # 8.2.4.1 - def encryptData(self, encryptKey, privParameters, dataToEncrypt): + def encrypt_data(self, encryptKey, privParameters, dataToEncrypt): """Encrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.encryptionError) @@ -166,7 +166,7 @@ def encryptData(self, encryptKey, privParameters, dataToEncrypt): return univ.OctetString(ciphertext), privParameters # 8.2.4.2 - def decryptData(self, decryptKey, privParameters, encryptedData): + def decrypt_data(self, decryptKey, privParameters, encryptedData): """Decrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.decryptionError) diff --git a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py index 9b6ab09c6..f79107195 100644 --- a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py +++ b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py @@ -16,18 +16,18 @@ class NoPriv(base.AbstractEncryptionService): SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol - def hashPassphrase(self, authProtocol, privKey): + def hash_passphrase(self, authProtocol, privKey): """Hash a passphrase.""" return - def localizeKey(self, authProtocol, privKey, snmpEngineID): + def localize_key(self, authProtocol, privKey, snmpEngineID): """Localize key.""" return - def encryptData(self, encryptKey, privParameters, dataToEncrypt): + def encrypt_data(self, encryptKey, privParameters, dataToEncrypt): """Encrypt data.""" raise error.StatusInformation(errorIndication=errind.noEncryption) - def decryptData(self, decryptKey, privParameters, encryptedData): + def decrypt_data(self, decryptKey, privParameters, encryptedData): """Decrypt data.""" raise error.StatusInformation(errorIndication=errind.noEncryption) diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py index f54919721..05944c360 100644 --- a/pysnmp/proto/secmod/rfc3414/service.py +++ b/pysnmp/proto/secmod/rfc3414/service.py @@ -9,6 +9,8 @@ # import sys import time +from typing import TYPE_CHECKING + from pyasn1.codec.ber import decoder, encoder, eoo from pyasn1.error import PyAsn1Error @@ -18,11 +20,16 @@ from pysnmp.proto.secmod.base import AbstractSecurityModel from pysnmp.proto.secmod.eso.priv import aes192, aes256, des3 from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth +from pysnmp.proto.secmod.rfc3414.auth.base import AbstractAuthenticationService from pysnmp.proto.secmod.rfc3414.priv import des, nopriv +from pysnmp.proto.secmod.rfc3414.priv.base import AbstractEncryptionService from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.rfc7860.auth import hmacsha2 from pysnmp.smi.error import NoSuchInstanceError +if TYPE_CHECKING: + from pysnmp.entity.engine import SnmpEngine + # API to rfc1905 protocol objects pMod = api.PROTOCOL_MODULES[api.SNMP_VERSION_2C] # noqa: N816 @@ -77,7 +84,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): """ SECURITY_MODEL_ID = 3 - AUTH_SERVICES = { + AUTH_SERVICES: dict[tuple, AbstractAuthenticationService] = { hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(), hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(), hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2( @@ -94,7 +101,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): ), noauth.NoAuth.SERVICE_ID: noauth.NoAuth(), } - PRIV_SERVICES = { + PRIV_SERVICES: dict[tuple, AbstractEncryptionService] = { des.Des.SERVICE_ID: des.Des(), des3.Des3.SERVICE_ID: des3.Des3(), aes.Aes.SERVICE_ID: aes.Aes(), @@ -129,13 +136,13 @@ def _close(self): if self._cache and not self._cache.isEmpty(): raise ValueError("Cache is not empty") - def __sec2usr(self, snmpEngine, securityName, securityEngineID=None): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - (usmUserEngineID,) = mibBuilder.importSymbols( + def __sec2usr(self, snmpEngine: "SnmpEngine", securityName, securityEngineID=None): + mibBuilder = snmpEngine.get_mib_builder() + (usmUserEngineID,) = mibBuilder.importSymbols( # type: ignore "SNMP-USER-BASED-SM-MIB", "usmUserEngineID" ) if self.__paramsBranchId != usmUserEngineID.branchVersionId: - usmUserName, usmUserSecurityName = mibBuilder.importSymbols( + usmUserName, usmUserSecurityName = mibBuilder.importSymbols( # type: ignore "SNMP-USER-BASED-SM-MIB", "usmUserName", "usmUserSecurityName" ) @@ -173,7 +180,7 @@ def __sec2usr(self, snmpEngine, securityName, securityEngineID=None): self.__securityToUserMap[k] = __userName if securityEngineID is None: - (snmpEngineID,) = mibBuilder.importSymbols( + (snmpEngineID,) = mibBuilder.importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) securityEngineID = snmpEngineID.syntax @@ -231,14 +238,12 @@ def __getUserInfo(mibInstrumController, securityEngineID, userName): pysnmpUsmKeyPrivLocalized, ) - def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - - (snmpEngineID,) = mibInstrumController.mibBuilder.importSymbols( + def __cloneUserInfo(self, snmpEngine: "SnmpEngine", securityEngineID, userName): + (snmpEngineID,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineID" ) # Proto entry - (usmUserEntry,) = mibInstrumController.mibBuilder.importSymbols( + (usmUserEntry,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "SNMP-USER-BASED-SM-MIB", "usmUserEntry" ) tblIdx1 = usmUserEntry.getInstIdFromIndices(snmpEngineID.syntax, userName) @@ -249,7 +254,7 @@ def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): usmUserAuthProtocol = usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx1) usmUserPrivProtocol = usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx1) # Get proto keys - (pysnmpUsmKeyEntry,) = mibInstrumController.mibBuilder.importSymbols( + (pysnmpUsmKeyEntry,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "PYSNMP-USM-MIB", "pysnmpUsmKeyEntry" ) pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode( @@ -264,7 +269,7 @@ def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): tblIdx2 = usmUserEntry.getInstIdFromIndices(securityEngineID, userName) # New row - mibInstrumController.writeVars( + snmpEngine.message_dispatcher.mib_instrum_controller.writeVars( (usmUserEntry.name + (13,) + tblIdx2, 4), **dict(snmpEngine=snmpEngine) ) @@ -290,14 +295,14 @@ def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): ).syntax = usmUserPrivProtocol.syntax # Localize and set keys - (pysnmpUsmKeyEntry,) = mibInstrumController.mibBuilder.importSymbols( + (pysnmpUsmKeyEntry,) = snmpEngine.get_mib_builder().importSymbols( # type: ignore "PYSNMP-USM-MIB", "pysnmpUsmKeyEntry" ) pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( pysnmpUsmKeyEntry.name + (1,) + tblIdx2 ) if usmUserAuthProtocol.syntax in self.AUTH_SERVICES: - localizeKey = self.AUTH_SERVICES[usmUserAuthProtocol.syntax].localizeKey + localizeKey = self.AUTH_SERVICES[usmUserAuthProtocol.syntax].localize_key localAuthKey = localizeKey(pysnmpUsmKeyAuth.syntax, securityEngineID) else: raise error.StatusInformation( @@ -311,7 +316,7 @@ def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): pysnmpUsmKeyEntry.name + (2,) + tblIdx2 ) if usmUserPrivProtocol.syntax in self.PRIV_SERVICES: - localizeKey = self.PRIV_SERVICES[usmUserPrivProtocol.syntax].localizeKey + localizeKey = self.PRIV_SERVICES[usmUserPrivProtocol.syntax].localize_key localPrivKey = localizeKey( usmUserAuthProtocol.syntax, pysnmpUsmKeyPriv.syntax, securityEngineID ) @@ -334,7 +339,7 @@ def __cloneUserInfo(self, snmpEngine, securityEngineID, userName): def __generateRequestOrResponseMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -346,10 +351,10 @@ def __generateRequestOrResponseMsg( securityStateReference, ctx, ): - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() snmpEngineID = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID")[ 0 - ].syntax + ].syntax # type: ignore msg = globalData # 3.1.1 @@ -415,7 +420,7 @@ def __generateRequestOrResponseMsg( usmUserPrivProtocol, usmUserPrivKeyLocalized, ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, + snmpEngine.message_dispatcher.mib_instrum_controller, securityEngineID, self.__sec2usr(snmpEngine, securityName, securityEngineID), ) @@ -429,7 +434,7 @@ def __generateRequestOrResponseMsg( usmUserPrivProtocol, usmUserPrivKeyLocalized, ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, + snmpEngine.message_dispatcher.mib_instrum_controller, self.wildcardSecurityEngineId, self.__sec2usr( snmpEngine, securityName, self.wildcardSecurityEngineId @@ -460,7 +465,7 @@ def __generateRequestOrResponseMsg( ) except NoSuchInstanceError: - (pysnmpUsmDiscovery,) = mibBuilder.importSymbols( + (pysnmpUsmDiscovery,) = mibBuilder.importSymbols( # type: ignore "__PYSNMP-USM-MIB", "pysnmpUsmDiscovery" ) reportUnknownName = not pysnmpUsmDiscovery.syntax @@ -477,7 +482,7 @@ def __generateRequestOrResponseMsg( snmpEngine, securityEngineID, self.__sec2usr(snmpEngine, securityName), - ) + ) # type: ignore debug.logger & debug.FLAG_SM and debug.logger( "__generateRequestOrResponseMsg: cloned USM user entry " @@ -520,7 +525,7 @@ def __generateRequestOrResponseMsg( debug.logger & debug.FLAG_SM and debug.logger( f"__generateRequestOrResponseMsg: {sys.exc_info()[1]}" ) - (snmpInGenErrs,) = mibBuilder.importSymbols( + (snmpInGenErrs,) = mibBuilder.importSymbols( # type: ignore "__SNMPv2-MIB", "snmpInGenErrs" ) snmpInGenErrs.syntax += 1 @@ -652,7 +657,7 @@ def __generateRequestOrResponseMsg( # 3.1.6.b if pdu.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS: - (snmpEngineBoots, snmpEngineTime) = mibBuilder.importSymbols( + (snmpEngineBoots, snmpEngineTime) = mibBuilder.importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineBoots", "snmpEngineTime" ) @@ -715,11 +720,11 @@ def __generateRequestOrResponseMsg( ) # noinspection PyUnboundLocalVariable - (encryptedData, privParameters) = privHandler.encryptData( + (encryptedData, privParameters) = privHandler.encrypt_data( usmUserPrivKeyLocalized, (snmpEngineBoots, snmpEngineTime, None), dataToEncrypt, - ) + ) # type: ignore securityParameters.setComponentByPosition( 5, @@ -792,7 +797,7 @@ def __generateRequestOrResponseMsg( # extra-wild hack to facilitate BER substrate in-place re-write securityParameters.setComponentByPosition( - 4, "\x00" * authHandler.digestLength + 4, "\x00" * authHandler.digest_length ) debug.logger & debug.FLAG_SM and debug.logger( @@ -827,7 +832,7 @@ def __generateRequestOrResponseMsg( raise error.StatusInformation(errorIndication=errind.serializationError) # noinspection PyUnboundLocalVariable - authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( + authenticatedWholeMsg = authHandler.authenticate_outgoing_message( usmUserAuthKeyLocalized, wholeMsg ) @@ -883,7 +888,7 @@ def __generateRequestOrResponseMsg( def generateRequestMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -910,7 +915,7 @@ def generateRequestMsg( def generateResponseMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, globalData, maxMessageSize, @@ -940,7 +945,7 @@ def generateResponseMsg( # 3.2 def processIncomingMsg( self, - snmpEngine, + snmpEngine: "SnmpEngine", messageProcessingModel, maxMessageSize, securityParameters, @@ -950,7 +955,7 @@ def processIncomingMsg( msg, ): """Process incoming SNMP message.""" - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() # 3.2.9 -- moved up here to be able to report # maxSizeResponseScopedPDU on error @@ -991,12 +996,14 @@ def processIncomingMsg( # Used for error reporting contextEngineId = mibBuilder.importSymbols( "__SNMP-FRAMEWORK-MIB", "snmpEngineID" - )[0].syntax + )[ + 0 + ].syntax # type: ignore contextName = b"" snmpEngineID = mibBuilder.importSymbols("__SNMP-FRAMEWORK-MIB", "snmpEngineID")[ 0 - ].syntax + ].syntax # type: ignore # 3.2.3 if ( @@ -1013,14 +1020,14 @@ def processIncomingMsg( debug.logger & debug.FLAG_SM and debug.logger( "processIncomingMsg: peer requested snmpEngineID discovery" ) - (usmStatsUnknownEngineIDs,) = mibBuilder.importSymbols( + (usmStatsUnknownEngineIDs,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsUnknownEngineIDs" ) usmStatsUnknownEngineIDs.syntax += 1 debug.logger & debug.FLAG_SM and debug.logger( "processIncomingMsg: null or malformed msgAuthoritativeEngineId" ) - (pysnmpUsmDiscoverable,) = mibBuilder.importSymbols( + (pysnmpUsmDiscoverable,) = mibBuilder.importSymbols( # type: ignore "__PYSNMP-USM-MIB", "pysnmpUsmDiscoverable" ) if pysnmpUsmDiscoverable.syntax: @@ -1082,7 +1089,7 @@ def processIncomingMsg( usmUserPrivProtocol, usmUserPrivKeyLocalized, ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, + snmpEngine.message_dispatcher.mib_instrum_controller, msgAuthoritativeEngineId, msgUserName, ) @@ -1100,7 +1107,7 @@ def processIncomingMsg( usmUserPrivProtocol, usmUserPrivKeyLocalized, ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, + snmpEngine.message_dispatcher.mib_instrum_controller, self.wildcardSecurityEngineId, msgUserName, ) @@ -1115,7 +1122,7 @@ def processIncomingMsg( ) ) - (usmStatsUnknownUserNames,) = mibBuilder.importSymbols( + (usmStatsUnknownUserNames,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames" ) usmStatsUnknownUserNames.syntax += 1 @@ -1136,7 +1143,7 @@ def processIncomingMsg( debug.logger & debug.FLAG_SM and debug.logger( f"processIncomingMsg: {sys.exc_info()[1]}" ) - (snmpInGenErrs,) = mibBuilder.importSymbols( + (snmpInGenErrs,) = mibBuilder.importSymbols( # type: ignore "__SNMPv2-MIB", "snmpInGenErrs" ) snmpInGenErrs.syntax += 1 @@ -1214,7 +1221,7 @@ def processIncomingMsg( if usmUserPrivProtocol != nopriv.NoPriv.SERVICE_ID: badSecIndication = "noAuthNoPriv wanted while priv expected" if badSecIndication: - (usmStatsUnsupportedSecLevels,) = mibBuilder.importSymbols( + (usmStatsUnsupportedSecLevels,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsUnsupportedSecLevels" ) usmStatsUnsupportedSecLevels.syntax += 1 @@ -1247,7 +1254,7 @@ def processIncomingMsg( hash = securityParameters.getComponentByPosition(4) try: - authHandler.authenticateIncomingMsg( + authHandler.authenticate_incoming_message( usmUserAuthKeyLocalized, hash, wholeMsg ) @@ -1255,7 +1262,7 @@ def processIncomingMsg( if ( len(hash) != 0 ): # don't throw error if hash is empty (and agent returned REPORT) - (usmStatsWrongDigests,) = mibBuilder.importSymbols( + (usmStatsWrongDigests,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsWrongDigests" ) usmStatsWrongDigests.syntax += 1 @@ -1284,9 +1291,9 @@ def processIncomingMsg( ) timerResolution = ( - snmpEngine.transportDispatcher is None + snmpEngine.transport_dispatcher is None and 1.0 - or snmpEngine.transportDispatcher.getTimerResolution() + or snmpEngine.transport_dispatcher.get_timer_resolution() # type: ignore ) expireAt = int(self.__expirationTimer + 300 / timerResolution) if expireAt not in self.__timelineExpQueue: @@ -1301,7 +1308,7 @@ def processIncomingMsg( if securityLevel == 3 or securityLevel == 2: if msgAuthoritativeEngineId == snmpEngineID: # Authoritative SNMP engine: use local notion (SF bug #1649032) - (snmpEngineBoots, snmpEngineTime) = mibBuilder.importSymbols( + (snmpEngineBoots, snmpEngineTime) = mibBuilder.importSymbols( # type: ignore "__SNMP-FRAMEWORK-MIB", "snmpEngineBoots", "snmpEngineTime" ) snmpEngineBoots = snmpEngineBoots.syntax @@ -1344,7 +1351,7 @@ def processIncomingMsg( ) > 150 ): - (usmStatsNotInTimeWindows,) = mibBuilder.importSymbols( + (usmStatsNotInTimeWindows,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsNotInTimeWindows" ) usmStatsNotInTimeWindows.syntax += 1 @@ -1376,9 +1383,9 @@ def processIncomingMsg( ) timerResolution = ( - snmpEngine.transportDispatcher is None + snmpEngine.transport_dispatcher is None and 1.0 - or snmpEngine.transportDispatcher.getTimerResolution() + or snmpEngine.transport_dispatcher.get_timer_resolution() # type: ignore ) expireAt = int(self.__expirationTimer + 300 / timerResolution) if expireAt not in self.__timelineExpQueue: @@ -1422,7 +1429,7 @@ def processIncomingMsg( ) try: - decryptedData = privHandler.decryptData( + decryptedData = privHandler.decrypt_data( usmUserPrivKeyLocalized, ( securityParameters.getComponentByPosition(1), @@ -1437,7 +1444,7 @@ def processIncomingMsg( ) except error.StatusInformation: - (usmStatsDecryptionErrors,) = mibBuilder.importSymbols( + (usmStatsDecryptionErrors,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors" ) usmStatsDecryptionErrors.syntax += 1 @@ -1463,7 +1470,7 @@ def processIncomingMsg( "processIncomingMsg: scopedPDU decoder failed %s" % sys.exc_info()[0] ) - (usmStatsDecryptionErrors,) = mibBuilder.importSymbols( + (usmStatsDecryptionErrors,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors" ) usmStatsDecryptionErrors.syntax += 1 @@ -1506,7 +1513,7 @@ def processIncomingMsg( # Delayed to include details if not msgUserName and not msgAuthoritativeEngineId: - (usmStatsUnknownUserNames,) = mibBuilder.importSymbols( + (usmStatsUnknownUserNames,) = mibBuilder.importSymbols( # type: ignore "__SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames" ) usmStatsUnknownUserNames.syntax += 1 @@ -1544,6 +1551,6 @@ def __expireTimelineInfo(self): del self.__timelineExpQueue[self.__expirationTimer] self.__expirationTimer += 1 - def receiveTimerTick(self, snmpEngine, timeNow): + def receiveTimerTick(self, snmpEngine: "SnmpEngine", timeNow): """Receive timer ticks from the transport layer.""" self.__expireTimelineInfo() diff --git a/pysnmp/proto/secmod/rfc3826/priv/aes.py b/pysnmp/proto/secmod/rfc3826/priv/aes.py index d2e76c1e2..187be0f5b 100644 --- a/pysnmp/proto/secmod/rfc3826/priv/aes.py +++ b/pysnmp/proto/secmod/rfc3826/priv/aes.py @@ -83,7 +83,7 @@ def __getDecryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime, salt): return privKey[: self.KEY_SIZE].asOctets(), univ.OctetString(iv).asOctets() - def hashPassphrase(self, authProtocol, privKey) -> univ.OctetString: + def hash_passphrase(self, authProtocol, privKey) -> univ.OctetString: """Hash a passphrase.""" if authProtocol == hmacmd5.HmacMd5.SERVICE_ID: hashAlgo = md5 @@ -95,7 +95,7 @@ def hashPassphrase(self, authProtocol, privKey) -> univ.OctetString: raise error.ProtocolError(f"Unknown auth protocol {authProtocol}") return localkey.hashPassphrase(privKey, hashAlgo) - def localizeKey(self, authProtocol, privKey, snmpEngineID) -> univ.OctetString: + def localize_key(self, authProtocol, privKey, snmpEngineID) -> univ.OctetString: """Localize a key.""" if authProtocol == hmacmd5.HmacMd5.SERVICE_ID: hashAlgo = md5 @@ -109,7 +109,7 @@ def localizeKey(self, authProtocol, privKey, snmpEngineID) -> univ.OctetString: return localPrivKey[: self.KEY_SIZE] # 3.2.4.1 - def encryptData(self, encryptKey, privParameters, dataToEncrypt): + def encrypt_data(self, encryptKey, privParameters, dataToEncrypt): """Encrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.encryptionError) @@ -135,7 +135,7 @@ def encryptData(self, encryptKey, privParameters, dataToEncrypt): return univ.OctetString(ciphertext), univ.OctetString(salt) # 3.2.4.2 - def decryptData(self, decryptKey, privParameters, encryptedData): + def decrypt_data(self, decryptKey, privParameters, encryptedData): """Decrypt data.""" if PysnmpCryptoError: raise error.StatusInformation(errorIndication=errind.decryptionError) diff --git a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py index bab9c6148..9ec57ec71 100644 --- a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py +++ b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py @@ -59,21 +59,21 @@ def __init__(self, oid): self.__digestLength = self.DIGEST_LENGTH[oid] self.__placeHolder = univ.OctetString((0,) * self.__digestLength).asOctets() - def hashPassphrase(self, authKey): + def hash_passphrase(self, authKey): """Hash a passphrase.""" return localkey.hashPassphrase(authKey, self.__hashAlgo) - def localizeKey(self, authKey, snmpEngineID): + def localize_key(self, authKey, snmpEngineID): """Localize a key.""" return localkey.localizeKey(authKey, snmpEngineID, self.__hashAlgo) @property - def digestLength(self): + def digest_length(self): """Return digest length.""" return self.__digestLength # 7.3.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): + def authenticate_outgoing_message(self, authKey, wholeMsg): """Authenticate outgoing message.""" # 7.3.1.1 location = wholeMsg.find(self.__placeHolder) @@ -96,7 +96,7 @@ def authenticateOutgoingMsg(self, authKey, wholeMsg): return wholeHead + mac + wholeTail # 7.3.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + def authenticate_incoming_message(self, authKey, authParameters, wholeMsg): """Authenticate incoming message.""" # 7.3.2.1 & 2 if len(authParameters) != self.__digestLength: diff --git a/tests/agent_context.py b/tests/agent_context.py index f0fa0a64b..66e9cf4df 100644 --- a/tests/agent_context.py +++ b/tests/agent_context.py @@ -22,29 +22,31 @@ async def start_agent( snmpEngine = engine.SnmpEngine() # Set up transport endpoint - config.addTransport( + config.add_transport( snmpEngine, udp.DOMAIN_NAME, - udp.UdpTransport().openServerMode(("localhost", AGENT_PORT)), + udp.UdpTransport().open_server_mode(("localhost", AGENT_PORT)), ) if enable_ipv6: - config.addTransport( + config.add_transport( snmpEngine, udp6.DOMAIN_NAME, - udp6.Udp6Transport().openServerMode(("localhost", AGENT_PORT)), + udp6.Udp6Transport().open_server_mode(("localhost", AGENT_PORT)), ) # Set up community data - config.addV1System(snmpEngine, "public", "public") + config.add_v1_system(snmpEngine, "public", "public") # Add SNMP v3 user - config.addV3User( + config.add_v3_user( snmpEngine, "usr-none-none", config.USM_AUTH_NONE, config.USM_PRIV_NONE ) - config.addV3User(snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1") + config.add_v3_user( + snmpEngine, "usr-sha-none", config.USM_AUTH_HMAC96_SHA, "authkey1" + ) - config.addV3User( + config.add_v3_user( snmpEngine, "usr-sha-aes", config.USM_AUTH_HMAC96_SHA, @@ -53,7 +55,7 @@ async def start_agent( "privkey1", ) - config.addV3User( + config.add_v3_user( snmpEngine, "usr-sha-aes256", config.USM_AUTH_HMAC96_SHA, @@ -63,19 +65,19 @@ async def start_agent( ) # Allow read MIB access for this user / securityModels at VACM - config.addVacmUser(snmpEngine, 1, "public", "noAuthNoPriv", (1, 3, 6), (1, 3, 6)) - config.addVacmUser(snmpEngine, 2, "public", "noAuthNoPriv", (1, 3, 6), (1, 3, 6)) - config.addVacmUser(snmpEngine, 3, "usr-none-none", "noAuthNoPriv", (1, 3, 6)) - config.addVacmUser(snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6)) - config.addVacmUser(snmpEngine, 3, "usr-sha-aes", "authPriv", (1, 3, 6)) - config.addVacmUser(snmpEngine, 3, "usr-sha-aes256", "authPriv", (1, 3, 6)) + config.add_vacm_user(snmpEngine, 1, "public", "noAuthNoPriv", (1, 3, 6), (1, 3, 6)) + config.add_vacm_user(snmpEngine, 2, "public", "noAuthNoPriv", (1, 3, 6), (1, 3, 6)) + config.add_vacm_user(snmpEngine, 3, "usr-none-none", "noAuthNoPriv", (1, 3, 6)) + config.add_vacm_user(snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6)) + config.add_vacm_user(snmpEngine, 3, "usr-sha-aes", "authPriv", (1, 3, 6)) + config.add_vacm_user(snmpEngine, 3, "usr-sha-aes256", "authPriv", (1, 3, 6)) # Configure SNMP context snmpContext = context.SnmpContext(snmpEngine) if enable_custom_objects: # --- create custom Managed Object Instances --- - mibBuilder = snmpContext.getMibInstrum().getMibBuilder() + mibBuilder = snmpContext.getMibInstrum().mibBuilder MibScalar, MibScalarInstance = mibBuilder.importSymbols( "SNMPv2-SMI", "MibScalar", "MibScalarInstance" @@ -118,7 +120,7 @@ def setValue(self, name, idx, value): if enable_table_creation: # --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- - mibBuilder = snmpContext.getMibInstrum().getMibBuilder() + mibBuilder = snmpContext.getMibInstrum().mibBuilder ( MibTable, @@ -192,9 +194,9 @@ def setValue(self, name, idx, value): cmdrsp.SetCommandResponder(snmpEngine, snmpContext) # Start the event loop - snmpEngine.transportDispatcher.jobStarted(1) + snmpEngine.transport_dispatcher.job_started(1) - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() # Wait for the agent to start await asyncio.sleep(1) @@ -234,5 +236,5 @@ async def __aenter__(self): return self.agent async def __aexit__(self, exc_type, exc_val, exc_tb): - self.agent.transportDispatcher.jobFinished(1) - self.agent.closeDispatcher() + self.agent.transport_dispatcher.job_finished(1) + self.agent.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_get.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_get.py index caf2dc9cb..02e665ffc 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_get.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_get.py @@ -31,7 +31,7 @@ async def test_v1_get(): name = pysnmp_errorStatus.namedValues.getName(errorStatus) assert name == "noError" - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -58,7 +58,7 @@ async def test_v1_get_ipv6(): name = pysnmp_errorStatus.namedValues.getName(errorStatus) assert name == "noError" - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() # TODO: @@ -85,7 +85,7 @@ async def test_v1_get_ipv6(): # except asyncio.TimeoutError: # assert False, "Test case timed out" # finally: -# snmpDispatcher.transportDispatcher.closeDispatcher() +# snmpDispatcher.transportDispatcher.close_dispatcher() # @pytest.mark.asyncio @@ -114,7 +114,7 @@ async def test_v1_get_ipv6(): # except asyncio.TimeoutError: # assert False, "Test case timed out" # finally: -# snmpDispatcher.transportDispatcher.closeDispatcher() +# snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -131,4 +131,4 @@ async def test_v1_get_no_access_object(): ) assert errorIndication is None assert errorStatus.prettyPrint() == "noSuchName" # v1 does not have noAccess - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_next.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_next.py index 3edf3fd02..e39d2ff82 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_next.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_next.py @@ -44,4 +44,4 @@ async def test_v1_next(): ) # IMPORTANT: MIB is needed to resolve this name assert type(varBinds[0][1]).__name__ == "ObjectIdentity" - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_set.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_set.py index c80045c2a..a55b6191c 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_set.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_set.py @@ -30,7 +30,7 @@ async def test_v1_set(): assert varBinds[0][1].prettyPrint() == "Shanghai" assert isinstance(varBinds[0][1], OctetString) - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -94,4 +94,4 @@ async def test_v1_set_table_creation(): assert len(objects_list) == object_counts + 4 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_walk.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_walk.py index 23cdf483d..38c47deb2 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_walk.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v1_walk.py @@ -32,7 +32,7 @@ async def test_v1_walk(): assert len(objects_list) == 267 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -65,4 +65,4 @@ async def test_v1_walk_subtree(): assert len(objects_list) == 8 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2_walk.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2_walk.py index 0e9422e55..e7426a926 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2_walk.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2_walk.py @@ -32,7 +32,7 @@ async def test_v2_walk(): # some agents have different v2 GET NEXT behavior assert len(objects_list) == 267 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -65,4 +65,4 @@ async def test_v2_walk_subtree(): assert len(objects_list) == 8 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulk.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulk.py index 6512cb013..6f8090659 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulk.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulk.py @@ -28,7 +28,7 @@ async def test_v2c_bulk(num_bulk): if num_bulk > 2: assert varBinds[2][0].prettyPrint() == "SNMPv2-MIB::sysContact.0" - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulkwalk.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulkwalk.py index 7250aa008..0f96a6727 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulkwalk.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_bulkwalk.py @@ -37,7 +37,7 @@ async def test_v2c_get_table_bulk(max_repetitions): assert len(objects_list) == 60 / max_repetitions - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -76,7 +76,7 @@ async def test_v2c_get_table_bulk_0_4_subtree(): assert index == 7 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -112,7 +112,7 @@ async def test_v2c_get_table_bulk_0_1_subtree(): assert index == 28 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -147,7 +147,7 @@ async def test_v2c_get_table_bulk_0_7(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 9 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -181,7 +181,7 @@ async def test_v2c_get_table_bulk_0_8(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 8 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -216,7 +216,7 @@ async def test_v2c_get_table_bulk_0_31(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 2 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -244,7 +244,7 @@ async def test_v2c_get_table_bulk_0_60(): assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysObjectID.0" assert len(objects_list) == 1 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -276,7 +276,7 @@ async def test_v2c_get_table_bulk_0_5_subtree(): assert len(varBinds) == 1 assert len(objects_list) == 4 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -308,4 +308,4 @@ async def test_v2c_get_table_bulk_0_6_subtree(): assert len(varBinds) == 4 assert len(objects_list) == 3 - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_get.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_get.py index 451226af8..584191e83 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_get.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_get.py @@ -21,7 +21,7 @@ async def test_v2_get(): assert varBinds[0][1].prettyPrint().startswith("PySNMP engine version") assert isinstance(varBinds[0][1], OctetString) - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -39,7 +39,7 @@ async def test_v2_get_no_access_object(): assert errorIndication is None assert errorStatus.prettyPrint() == "noAccess" # v2c and v3 use noAccess - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() @pytest.mark.asyncio @@ -59,4 +59,4 @@ async def test_v2_get_legacy_object(): assert ( errorStatus.prettyPrint() == "noAccess" ) # PySMI <1.3.0 generates such objects - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_next.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_next.py index 8e01a1a8a..2f43c497d 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_next.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_next.py @@ -38,4 +38,4 @@ async def test_v2_next(): assert len(varBinds) == 1 assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysObjectID.0" - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_set.py b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_set.py index b65cfa751..3e53011ef 100644 --- a/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_set.py +++ b/tests/hlapi/v1arch/asyncio/manager/cmdgen/test_v1arch_v2c_set.py @@ -23,4 +23,4 @@ async def test_v2_set(): assert varBinds[0][1].prettyPrint() == "Shanghai" assert isinstance(varBinds[0][1], OctetString) - snmpDispatcher.transportDispatcher.closeDispatcher() + snmpDispatcher.transportDispatcher.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_default-v1-trap.py b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_default-v1-trap.py index 113e2d232..b68017653 100644 --- a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_default-v1-trap.py +++ b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_default-v1-trap.py @@ -30,7 +30,7 @@ async def test_send_trap_enterprise_specific(): ), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [1] @@ -56,7 +56,7 @@ async def test_send_trap_generic(): ), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [1] @@ -65,7 +65,7 @@ async def test_send_trap_generic(): async def test_send_trap_custom_mib(): async with ManagerContextManager() as (_, message_count): snmpEngine = SnmpEngine() - mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + mibBuilder = snmpEngine.get_mib_builder() (sysUpTime,) = mibBuilder.importSymbols("__SNMPv2-MIB", "sysUpTime") sysUpTime.syntax = TimeTicks(12345) @@ -87,6 +87,6 @@ async def test_send_trap_custom_mib(): ), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [1] diff --git a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-inform.py b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-inform.py index 004e70d29..fd3537284 100644 --- a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-inform.py +++ b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-inform.py @@ -31,4 +31,4 @@ async def test_send_v3_inform(): isinstance(varBinds[0][1], TimeTicks) isinstance(varBinds[1][1], ObjectIdentifier) isinstance(varBinds[2][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-trap.py b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-trap.py index 6e84d452c..b1b3c7069 100644 --- a/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-trap.py +++ b/tests/hlapi/v3arch/asyncio/agent/ntforg/test_v3-trap.py @@ -20,7 +20,7 @@ async def test_send_v3_trap_notification(): NotificationType(ObjectIdentity("IF-MIB", "linkDown")), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [1] @@ -39,7 +39,7 @@ async def test_send_v3_trap_notification_none(): NotificationType(ObjectIdentity("IF-MIB", "linkDown")), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [1] @@ -58,6 +58,6 @@ async def test_send_v3_trap_notification_invalid_user(): NotificationType(ObjectIdentity("IF-MIB", "linkDown")), ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() await asyncio.sleep(1) assert message_count == [0] diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_custom_asn1_mib_search_path.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_custom_asn1_mib_search_path.py index 4cffd8cc4..9df75de0b 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_custom_asn1_mib_search_path.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_custom_asn1_mib_search_path.py @@ -24,4 +24,4 @@ async def test_custom_asn1_mib_search_path(): assert len(varBinds) == 1 assert varBinds[0][0].prettyPrint() == "IF-MIB::ifInOctets.1" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_lcd_configurator.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_lcd_configurator.py index 159946d37..59303f57d 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_lcd_configurator.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_lcd_configurator.py @@ -6,10 +6,10 @@ from pysnmp.hlapi.v3arch.asyncio.lcd import CommandGeneratorLcdConfigurator -@mock.patch("pysnmp.entity.config.addV3User") -@mock.patch("pysnmp.entity.config.delV3User") +@mock.patch("pysnmp.entity.config.add_v3_user") +@mock.patch("pysnmp.entity.config.delete_v3_user") @pytest.mark.asyncio -async def test_usm_auth_cache_cleared(delV3User, addV3User): +async def test_usm_auth_cache_cleared(delete_v3_user, add_v3_user): """ Ensure auth cache is cleared when auth data is changed. """ @@ -27,7 +27,7 @@ async def test_usm_auth_cache_cleared(delV3User, addV3User): lcd = CommandGeneratorLcdConfigurator() initialAuthData = UsmUserData(**authDataValues) lcd.configure(snmpEngine, initialAuthData, transportTarget) - addV3User.assert_called_with( + add_v3_user.assert_called_with( snmpEngine, initialAuthData.userName, initialAuthData.authProtocol, @@ -41,10 +41,10 @@ async def test_usm_auth_cache_cleared(delV3User, addV3User): ) # Ensure we do not add/delete if nothing changes - addV3User.reset_mock() + add_v3_user.reset_mock() lcd.configure(snmpEngine, initialAuthData, transportTarget) - addV3User.assert_not_called() - delV3User.assert_not_called() + add_v3_user.assert_not_called() + delete_v3_user.assert_not_called() changeAuthValues = { "authKey": "authKey2", @@ -54,20 +54,20 @@ async def test_usm_auth_cache_cleared(delV3User, addV3User): } for field, value in changeAuthValues.items(): - addV3User.reset_mock() - delV3User.reset_mock() + add_v3_user.reset_mock() + delete_v3_user.reset_mock() authDataValues[field] = value authData = UsmUserData(**authDataValues) lcd.configure(snmpEngine, authData, transportTarget) - delV3User.assert_called_with( + delete_v3_user.assert_called_with( snmpEngine, authData.userName, authData.securityEngineId, ) - addV3User.assert_called_with( + add_v3_user.assert_called_with( snmpEngine, authData.userName, authData.authProtocol, diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_get.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_get.py index 85f3173ce..dcd7edaf0 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_get.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_get.py @@ -27,7 +27,7 @@ async def test_v1_get(): assert varBinds[0][1].prettyPrint().startswith("PySNMP engine version") assert isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -49,7 +49,7 @@ async def test_v1_get_ipv6(): assert varBinds[0][1].prettyPrint().startswith("PySNMP engine version") assert isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() def test_v1_get_timeout_invalid_target(): @@ -76,7 +76,7 @@ async def run_get(): except asyncio.TimeoutError: assert False, "Test case timed out" finally: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -106,7 +106,7 @@ async def run_get(): except asyncio.TimeoutError: assert False, "Test case timed out" finally: - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -124,4 +124,4 @@ async def test_v1_get_no_access_object(): ) assert errorIndication is None assert errorStatus.prettyPrint() == "noSuchName" # v1 does not have noAccess - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_next.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_next.py index 2f35621fb..fe8d61bbc 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_next.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_next.py @@ -45,4 +45,4 @@ async def test_v1_next(): ) # IMPORTANT: MIB is needed to resolve this name assert type(varBinds[0][1]).__name__ == "ObjectIdentity" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_set.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_set.py index 3675078cb..762f52b65 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_set.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_set.py @@ -22,7 +22,7 @@ async def test_v1_set(): assert varBinds[0][1].prettyPrint() == "Shanghai" assert isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_walk.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_walk.py index ada26dfab..f8a902a0e 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_walk.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v1_walk.py @@ -35,7 +35,7 @@ async def test_v1_walk(): assert len(objects_list) == 267 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -93,7 +93,7 @@ async def test_v1_walk_mib(): ): assert content.count(".") == 1 # fully resolved. - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -127,4 +127,4 @@ async def test_v1_walk_subtree(): assert len(objects_list) == 8 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2_walk.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2_walk.py index 01fa2037c..23aad0363 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2_walk.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2_walk.py @@ -33,7 +33,7 @@ async def test_v2_walk(): # some agents have different v2 GET NEXT behavior assert len(objects_list) == 267 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -67,4 +67,4 @@ async def test_v2_walk_subtree(): assert len(objects_list) == 8 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulk.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulk.py index e619950d9..477cfc537 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulk.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulk.py @@ -30,7 +30,7 @@ async def test_v2c_bulk(num_bulk): if num_bulk > 2: assert varBinds[2][0].prettyPrint() == "SNMPv2-MIB::sysContact.0" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -49,7 +49,7 @@ async def test_v2c_bulk_non_exist(): ) assert isinstance(errorIndication, RequestTimedOut) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulkwalk.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulkwalk.py index fdf6d7ffc..8fa953db1 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulkwalk.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_bulkwalk.py @@ -38,7 +38,7 @@ async def test_v2c_get_table_bulk(max_repetitions): assert len(objects_list) == 60 / max_repetitions - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -78,7 +78,7 @@ async def test_v2c_get_table_bulk_0_4_subtree(): assert index == 7 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -115,7 +115,7 @@ async def test_v2c_get_table_bulk_0_1_subtree(): assert index == 28 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -151,7 +151,7 @@ async def test_v2c_get_table_bulk_0_7(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 9 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -186,7 +186,7 @@ async def test_v2c_get_table_bulk_0_8(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 8 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -222,7 +222,7 @@ async def test_v2c_get_table_bulk_0_31(): # assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysName.0" assert len(objects_list) == 2 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -251,7 +251,7 @@ async def test_v2c_get_table_bulk_0_60(): assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysObjectID.0" assert len(objects_list) == 1 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -284,7 +284,7 @@ async def test_v2c_get_table_bulk_0_5_subtree(): assert len(varBinds) == 1 assert len(objects_list) == 4 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -317,4 +317,4 @@ async def test_v2c_get_table_bulk_0_6_subtree(): assert len(varBinds) == 4 assert len(objects_list) == 3 - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_get.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_get.py index 31127f1d6..fcbe42c28 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_get.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_get.py @@ -22,7 +22,7 @@ async def test_v2_get(): assert varBinds[0][1].prettyPrint().startswith("PySNMP engine version") assert isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -41,7 +41,7 @@ async def test_v2_get_no_access_object(): assert errorIndication is None assert errorStatus.prettyPrint() == "noAccess" # v2c and v3 use noAccess - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -62,4 +62,4 @@ async def test_v2_get_legacy_object(): assert ( errorStatus.prettyPrint() == "noAccess" ) # PySMI <1.3.0 generates such objects - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_next.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_next.py index 788b3afcf..2e2790a97 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_next.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_next.py @@ -39,4 +39,4 @@ async def test_v2_next(): assert len(varBinds) == 1 assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysObjectID.0" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_set.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_set.py index ae7a27f87..b08643c7c 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_set.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v2c_set.py @@ -24,4 +24,4 @@ async def test_v2_set(): assert varBinds[0][1].prettyPrint() == "Shanghai" assert isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_none_none.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_none_none.py index 9334d4ae7..2f3477197 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_none_none.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_none_none.py @@ -40,4 +40,4 @@ async def test_usm_no_auth_no_priv_wrong_user(): assert isinstance(errorIndication, UnknownUserName) assert str(errorIndication) == "Unknown USM user" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes128.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes128.py index fda6399fa..ac590b78e 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes128.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes128.py @@ -29,7 +29,7 @@ async def test_usm_sha_aes128(): assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysDescr.0" isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -54,7 +54,7 @@ async def test_usm_sha_aes128_wrong_auth(): assert isinstance(errorIndication, WrongDigest) assert str(errorIndication) == "Wrong SNMP PDU digest" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -82,7 +82,7 @@ async def test_usm_sha_aes128_wrong_priv(): == "Ciphering services not available or ciphertext is broken" ) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -107,4 +107,4 @@ async def test_usm_sha_aes128_wrong_user(): assert isinstance(errorIndication, UnknownUserName) assert str(errorIndication) == "Unknown USM user" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes256.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes256.py index 124000e0f..b5aa1fbea 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes256.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_aes256.py @@ -29,7 +29,7 @@ async def test_usm_sha_aes256(): assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysDescr.0" isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -54,7 +54,7 @@ async def test_usm_sha_aes256_wrong_auth(): assert isinstance(errorIndication, WrongDigest) assert str(errorIndication) == "Wrong SNMP PDU digest" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -79,4 +79,4 @@ async def test_usm_sha_aes256_wrong_user(): assert isinstance(errorIndication, UnknownUserName) assert str(errorIndication) == "Unknown USM user" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_none.py b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_none.py index ed822fc68..9b9451c66 100644 --- a/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_none.py +++ b/tests/hlapi/v3arch/asyncio/manager/cmdgen/test_v3_usm_sha_none.py @@ -27,7 +27,7 @@ async def test_usm_sha_none(): assert varBinds[0][0].prettyPrint() == "SNMPv2-MIB::sysDescr.0" isinstance(varBinds[0][1], OctetString) - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -50,7 +50,7 @@ async def test_usm_sha_none_wrong_auth(): assert isinstance(errorIndication, WrongDigest) assert str(errorIndication) == "Wrong SNMP PDU digest" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() @pytest.mark.asyncio @@ -73,4 +73,4 @@ async def test_usm_sha_none_wrong_user(): assert isinstance(errorIndication, UnknownUserName) assert str(errorIndication) == "Unknown USM user" - snmpEngine.closeDispatcher() + snmpEngine.close_dispatcher() diff --git a/tests/manager_context.py b/tests/manager_context.py index 67432d82a..b925fad6a 100644 --- a/tests/manager_context.py +++ b/tests/manager_context.py @@ -23,21 +23,21 @@ async def start_manager( # Transport setup # UDP over IPv4 - config.addTransport( + config.add_transport( snmpEngine, udp.DOMAIN_NAME, - udp.UdpTransport().openServerMode(("localhost", MANAGER_PORT)), + udp.UdpTransport().open_server_mode(("localhost", MANAGER_PORT)), ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping - config.addV1System(snmpEngine, "public", "public") + config.add_v1_system(snmpEngine, "public", "public") # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES - config.addV3User( + config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -48,7 +48,7 @@ async def start_manager( # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes - config.addV3User( + config.add_v3_user( snmpEngine, "usr-md5-des", config.USM_AUTH_HMAC96_MD5, @@ -60,7 +60,7 @@ async def start_manager( # user: usr-none-none, auth: NONE, priv: NONE # this USM entry is used for TRAP receiving purposes - config.addV3User( + config.add_v3_user( snmpEngine, "usr-none-none", config.USM_AUTH_NONE, @@ -79,9 +79,9 @@ def cbFun( receiver = ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run I/O dispatcher which would receive queries and send confirmations - snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish + snmpEngine.transport_dispatcher.job_started(1) # this job would never finish - snmpEngine.openDispatcher() + snmpEngine.open_dispatcher() # Wait for the manager to start await asyncio.sleep(1) @@ -116,5 +116,5 @@ async def __aenter__(self): async def __aexit__(self, exc_type, exc_val, exc_tb): self.receiver.close(self.manager) - self.manager.transportDispatcher.jobFinished(1) - self.manager.closeDispatcher() + self.manager.transport_dispatcher.job_finished(1) + self.manager.close_dispatcher()