diff --git a/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py deleted file mode 100644 index dc6603f98..000000000 --- a/examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py +++ /dev/null @@ -1,170 +0,0 @@ -""" -Implementing scalar MIB objects -+++++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/GETNEXT queries with the following options: - -* SNMPv1 or SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:161 -* over IPv6/UDP, listening at [::1]:161 -* serving two Managed Objects Instances (sysDescr.0 and sysUptime.0) - -Either of the following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 -| $ snmpwalk -v2c -c public udp6:[::1] .1.3.6 - -The Command Receiver below uses two distinct transports for communication -with Command Generators - UDP over IPv4 and UDP over IPv6. - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp, udp6, unix -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto import api -import time, bisect - - -class SysDescr: - name = (1, 3, 6, 1, 2, 1, 1, 1, 0) - - def __eq__(self, other): - return self.name == other - - def __ne__(self, other): - return self.name != other - - def __lt__(self, other): - return self.name < other - - def __le__(self, other): - return self.name <= other - - def __gt__(self, other): - return self.name > other - - def __ge__(self, other): - return self.name >= other - - def __call__(self, protoVer): - return api.protoModules[protoVer].OctetString( - "PySNMP example command responder" - ) - - -class Uptime: - name = (1, 3, 6, 1, 2, 1, 1, 3, 0) - birthday = time.time() - - def __eq__(self, other): - return self.name == other - - def __ne__(self, other): - return self.name != other - - def __lt__(self, other): - return self.name < other - - def __le__(self, other): - return self.name <= other - - def __gt__(self, other): - return self.name > other - - def __ge__(self, other): - return self.name >= other - - def __call__(self, protoVer): - return api.protoModules[protoVer].TimeTicks((time.time() - self.birthday) * 100) - - -mibInstr = (SysDescr(), Uptime()) # sorted by object name - -mibInstrIdx = {} -for mibVar in mibInstr: - mibInstrIdx[mibVar.name] = mibVar - - -def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): - while wholeMsg: - msgVer = api.decodeMessageVersion(wholeMsg) - if msgVer in api.protoModules: - pMod = api.protoModules[msgVer] - else: - print("Unsupported SNMP version %s" % msgVer) - return - reqMsg, wholeMsg = decoder.decode( - wholeMsg, - asn1Spec=pMod.Message(), - ) - rspMsg = pMod.apiMessage.getResponse(reqMsg) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - reqPDU = pMod.apiMessage.getPDU(reqMsg) - varBinds = [] - pendingErrors = [] - errorIndex = 0 - # GETNEXT PDU - if reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()): - # Produce response var-binds - for oid, val in pMod.apiPDU.getVarBinds(reqPDU): - errorIndex = errorIndex + 1 - # Search next OID to report - nextIdx = bisect.bisect(mibInstr, oid) - if nextIdx == len(mibInstr): - # Out of MIB - varBinds.append((oid, val)) - pendingErrors.append((pMod.apiPDU.setEndOfMibError, errorIndex)) - else: - # Report value if OID is found - varBinds.append((mibInstr[nextIdx].name, mibInstr[nextIdx](msgVer))) - elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()): - for oid, val in pMod.apiPDU.getVarBinds(reqPDU): - if oid in mibInstrIdx: - varBinds.append((oid, mibInstrIdx[oid](msgVer))) - else: - # No such instance - varBinds.append((oid, val)) - pendingErrors.append( - (pMod.apiPDU.setNoSuchInstanceError, errorIndex) - ) - break - else: - # Report unsupported request type - pMod.apiPDU.setErrorStatus(rspPDU, "genErr") - pMod.apiPDU.setVarBinds(rspPDU, varBinds) - # Commit possible error indices to response PDU - for f, i in pendingErrors: - f(rspPDU, i) - transportDispatcher.sendMessage( - encoder.encode(rspMsg), transportDomain, transportAddress - ) - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() -transportDispatcher.registerRecvCbFun(cbFun) - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openServerMode(("localhost", 161)) -) - -# UDP/IPv6 -transportDispatcher.registerTransport( - udp6.domainName, udp6.Udp6SocketTransport().openServerMode(("::1", 161)) -) - -## Local domain socket -# transportDispatcher.registerTransport( -# unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-agent') -# ) - -transportDispatcher.jobStarted(1) - -try: - # Dispatcher will never finish as job#1 never reaches zero - transportDispatcher.runDispatcher() -except: - transportDispatcher.closeDispatcher() - raise diff --git a/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py deleted file mode 100644 index 6cfe915c5..000000000 --- a/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -INFORM over multiple transports -+++++++++++++++++++++++++++++++ - -The following script sends SNMP INFORM notification using the following options: - -* with SNMPv2c -* with community name 'public' -* over IPv4/UDP and IPv6/UDP -* send INFORM notification -* to a Manager at demo.pysnmp.com:162 and [::1]:162 -* with TRAP ID 'coldStart' specified as an OID - -The following Net-SNMP command will produce similar SNMP notification: - -| $ snmpinform -v2c -c public udp:demo.pysnmp.com 0 1.3.6.1.6.3.1.1.5.1 -| $ snmpinform -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 - -"""# -from time import time -from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher -from pysnmp.carrier.asynsock.dgram import udp, udp6 -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto.api import v2c as pMod - -# Build PDU -reqPDU = pMod.InformRequestPDU() -pMod.apiTrapPDU.setDefaults(reqPDU) - -# Build message -trapMsg = pMod.Message() -pMod.apiMessage.setDefaults(trapMsg) -pMod.apiMessage.setCommunity(trapMsg, "public") -pMod.apiMessage.setPDU(trapMsg, reqPDU) - -startedAt = time() - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise Exception("Request timed out") - - -# noinspection PyUnusedLocal,PyUnusedLocal -def cbRecvFun( - transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus: - print(errorStatus.prettyPrint()) - else: - print("INFORM message delivered, response var-binds follow") - for oid, val in pMod.apiPDU.getVarBinds(rspPDU): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.jobFinished(1) - return wholeMsg - - -transportDispatcher = AsynsockDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) -transportDispatcher.sendMessage( - encoder.encode(trapMsg), udp.domainName, ('demo.pysnmp.com', 162) -) -transportDispatcher.jobStarted(1) - -# UDP/IPv6 -# transportDispatcher.registerTransport( -# udp6.domainName, udp6.Udp6SocketTransport().openClientMode() -# ) -# transportDispatcher.sendMessage( -# encoder.encode(trapMsg), udp6.domainName, ('::1', 162) -# ) -# transportDispatcher.jobStarted(1) - -# Dispatcher will finish as all scheduled messages are sent -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py b/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py deleted file mode 100644 index a06f82565..000000000 --- a/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py +++ /dev/null @@ -1,76 +0,0 @@ -""" -TRAP over multiple transports -+++++++++++++++++++++++++++++ - -The following script sends two SNMP TRAP notification using the -following options: - -* with SNMPv1 -* with community name 'public' -* over IPv4/UDP and IPv6/UDP -* send TRAP notification -* to a Manager at demo.pysnmp.com:162 and [::1] -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: -* with default Uptime value -* with default Agent Address with '127.0.0.1' -* overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 - -The following Net-SNMP commands will produce similar SNMP notification: - -| $ snmptrap -v1 -c public udp:demo.pysnmp.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 -| $ snmptrap -v1 -c public udp6:[::1] 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp, udp6, unix -from pyasn1.codec.ber import encoder -from pysnmp.proto import api - -# Protocol version to use -pMod = api.protoModules[api.protoVersion1] -# pMod = api.protoModules[api.protoVersion2c] - -# Build PDU -trapPDU = pMod.TrapPDU() -pMod.apiTrapPDU.setDefaults(trapPDU) - -# Traps have quite different semantics across proto versions -if pMod == api.protoModules[api.protoVersion1]: - pMod.apiTrapPDU.setEnterprise(trapPDU, (1, 3, 6, 1, 1, 2, 3, 4, 1)) - pMod.apiTrapPDU.setGenericTrap(trapPDU, "coldStart") - -# Build message -trapMsg = pMod.Message() -pMod.apiMessage.setDefaults(trapMsg) -pMod.apiMessage.setCommunity(trapMsg, "public") -pMod.apiMessage.setPDU(trapMsg, trapPDU) - -transportDispatcher = AsyncoreDispatcher() - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) -transportDispatcher.sendMessage( - encoder.encode(trapMsg), udp.domainName, ('demo.pysnmp.com', 162) -) - -# UDP/IPv6 -transportDispatcher.registerTransport( - udp6.domainName, udp6.Udp6SocketTransport().openClientMode() -) -transportDispatcher.sendMessage(encoder.encode(trapMsg), udp6.domainName, ("::1", 162)) - -## Local domain socket -# transportDispatcher.registerTransport( -# unix.domainName, unix.UnixSocketTransport().openClientMode() -# ) -# transportDispatcher.sendMessage( -# encoder.encode(trapMsg), unix.domainName, '/tmp/snmp-manager' -# ) - -# Dispatcher will finish as all scheduled messages are sent -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py b/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py deleted file mode 100644 index 7bfb85744..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -Broadcast SNMP message (IPv4) -+++++++++++++++++++++++++++++ - -Send SNMP GET request to broadcast address and wait for respons(es): - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to all Agents via broadcast address 255.255.255.255:161 -* for OIDs in tuple form - -Here we send out a single SNMP request and wait for potentially many SNMP -responses from multiple SNMP Agents listening in local broadcast domain. -Since we can't predict the exact number of Agents responding, this script -just waits for arbitrary time for collecting all responses. This technology -is also known as SNMP-based discovery. - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v2c -c public -ObentU 255.255.255.255 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto import api -from time import time - -# Broadcast manager settings -maxWaitForResponses = 5 -maxNumberResponses = 10 - -# Protocol version to use -# pMod = api.protoModules[api.protoVersion1] -pMod = api.protoModules[api.protoVersion2c] - -# Build PDU -reqPDU = pMod.GetRequestPDU() -pMod.apiPDU.setDefaults(reqPDU) -pMod.apiPDU.setVarBinds( - reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null(""))) -) - -# Build message -reqMsg = pMod.Message() -pMod.apiMessage.setDefaults(reqMsg) -pMod.apiMessage.setCommunity(reqMsg, "public") -pMod.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -class StopWaiting(Exception): - pass - - -def cbTimerFun(timeNow): - if timeNow - startedAt > maxWaitForResponses: - raise StopWaiting() - - -# noinspection PyUnusedLocal,PyUnusedLocal -def cbRecvFun( - transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus: - print(errorStatus.prettyPrint()) - else: - for oid, val in pMod.apiPDU.getVarBinds(rspPDU): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.jobFinished(1) - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -# UDP/IPv4 -udpSocketTransport = udp.UdpSocketTransport().openClientMode().enableBroadcast() -transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) - -# Pass message to dispatcher -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, ("255.255.255.255", 161) -) - -# wait for a maximum of 10 responses or time out -transportDispatcher.jobStarted(1, maxNumberResponses) - -# Dispatcher will finish as all jobs counter reaches zero -try: - transportDispatcher.runDispatcher() -except StopWaiting: - transportDispatcher.closeDispatcher() -else: - raise diff --git a/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py b/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py deleted file mode 100644 index 73b971252..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Fetch scalar MIB variables (SNMPv1) -+++++++++++++++++++++++++++++++++++ - -Perform SNMP GET operation with the following options: - -* with SNMPv1, community 'public' -* over IPv4/UDP -* to an Agent at demo.pysnmp.com:161 -* for OIDs in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v1 -c public -ObentU demo.pysnmp.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp, udp6, unix -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto import api -from time import time - -# Protocol version to use -pMod = api.protoModules[api.protoVersion1] -# pMod = api.protoModules[api.protoVersion2c] - -# Build PDU -reqPDU = pMod.GetRequestPDU() -pMod.apiPDU.setDefaults(reqPDU) -pMod.apiPDU.setVarBinds( - reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null(""))) -) - -# Build message -reqMsg = pMod.Message() -pMod.apiMessage.setDefaults(reqMsg) -pMod.apiMessage.setCommunity(reqMsg, "public") -pMod.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise Exception("Request timed out") - - -# noinspection PyUnusedLocal,PyUnusedLocal -def cbRecvFun( - transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus: - print(errorStatus.prettyPrint()) - else: - for oid, val in pMod.apiPDU.getVarBinds(rspPDU): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.jobFinished(1) - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) - -# Pass message to dispatcher -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, ('demo.pysnmp.com', 161) -) -transportDispatcher.jobStarted(1) - -## UDP/IPv6 (second copy of the same PDU will be sent) -# transportDispatcher.registerTransport( -# udp6.domainName, udp6.Udp6SocketTransport().openClientMode() -# ) - -# Pass message to dispatcher -# transportDispatcher.sendMessage( -# encoder.encode(reqMsg), udp6.domainName, ('::1', 161) -# ) -# transportDispatcher.jobStarted(1) - -## Local domain socket -# transportDispatcher.registerTransport( -# unix.domainName, unix.UnixSocketTransport().openClientMode() -# ) -# -# Pass message to dispatcher -# transportDispatcher.sendMessage( -# encoder.encode(reqMsg), unix.domainName, '/tmp/snmp-agent' -# ) -# transportDispatcher.jobStarted(1) - -# Dispatcher will finish as job#1 counter reaches zero -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py b/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py deleted file mode 100644 index fc8b16d4b..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py +++ /dev/null @@ -1,127 +0,0 @@ -""" -Bulk walk Agent MIB (SNMPv2c) -+++++++++++++++++++++++++++++ - -Perform SNMP GETBULK operation with the following options: - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at demo.pysnmp.com:161 -* for OID in tuple form -* with non-repeaters=0 and max-repeaters=25 - -This script performs similar to the following Net-SNMP command: - -| $ snmpbulkwalk -v2c -c public -ObentU -Cn0 -Cr25 demo.pysnmp.com 1.3.6 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto.api import v2c -from time import time - -# SNMP table header -headVars = [v2c.ObjectIdentifier((1, 3, 6))] - -# Build PDU -reqPDU = v2c.GetBulkRequestPDU() -v2c.apiBulkPDU.setDefaults(reqPDU) -v2c.apiBulkPDU.setNonRepeaters(reqPDU, 0) -v2c.apiBulkPDU.setMaxRepetitions(reqPDU, 25) -v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars]) - -# Build message -reqMsg = v2c.Message() -v2c.apiMessage.setDefaults(reqMsg) -v2c.apiMessage.setCommunity(reqMsg, "public") -v2c.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise Exception("Request timed out") - - -# noinspection PyUnusedLocal -def cbRecvFun( - transportDispatcher, - transportDomain, - transportAddress, - wholeMsg, - reqPDU=reqPDU, - headVars=headVars, -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message()) - - rspPDU = v2c.apiMessage.getPDU(rspMsg) - - # Match response to request - if v2c.apiBulkPDU.getRequestID(reqPDU) == v2c.apiBulkPDU.getRequestID(rspPDU): - # Format var-binds table - varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, rspPDU) - - # Check for SNMP errors reported - errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU) - if errorStatus and errorStatus != 2: - errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU) - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[int(errorIndex) - 1] or "?", - ) - ) - transportDispatcher.jobFinished(1) - break - - # Report SNMP table - for tableRow in varBindTable: - for name, val in tableRow: - print( - "from: {}, {} = {}".format( - transportAddress, name.prettyPrint(), val.prettyPrint() - ) - ) - - # Stop on EOM - for oid, val in varBindTable[-1]: - if not isinstance(val, v2c.Null): - break - else: - transportDispatcher.jobFinished(1) - - # Generate request for next row - v2c.apiBulkPDU.setVarBinds( - reqPDU, [(x, v2c.null) for x, y in varBindTable[-1]] - ) - v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID()) - transportDispatcher.sendMessage( - encoder.encode(reqMsg), transportDomain, transportAddress - ) - global startedAt - if time() - startedAt > 3: - raise Exception("Request timed out") - startedAt = time() - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, ('demo.pysnmp.com', 161) -) -transportDispatcher.jobStarted(1) - -# Dispatcher will finish as job#1 counter reaches zero -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py b/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py deleted file mode 100644 index 3e7f3c47e..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py +++ /dev/null @@ -1,114 +0,0 @@ -""" -Walk Agent MIB (SNMPv1) -+++++++++++++++++++++++ - -Perform SNMP GETNEXT operation with the following options: - -* with SNMPv1, community 'public' -* over IPv4/UDP -* to an Agent at demo.pysnmp.com:161 -* for OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v1 -c public -ObentU demo.pysnmp.com 1.3.6 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto import api -from time import time - -# Protocol version to use -pMod = api.protoModules[api.protoVersion1] -# pMod = api.protoModules[api.protoVersion2c] - -# SNMP table header -headVars = [pMod.ObjectIdentifier((1, 3, 6))] - -# Build PDU -reqPDU = pMod.GetNextRequestPDU() -pMod.apiPDU.setDefaults(reqPDU) -pMod.apiPDU.setVarBinds(reqPDU, [(x, pMod.null) for x in headVars]) - -# Build message -reqMsg = pMod.Message() -pMod.apiMessage.setDefaults(reqMsg) -pMod.apiMessage.setCommunity(reqMsg, "public") -pMod.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise Exception("Request timed out") - - -# noinspection PyUnusedLocal -def cbRecvFun( - transportDispatcher, - transportDomain, - transportAddress, - wholeMsg, - reqPDU=reqPDU, - headVars=headVars, -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus and errorStatus != 2: - raise Exception(errorStatus) - # Format var-binds table - varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU) - # Report SNMP table - for tableRow in varBindTable: - for name, val in tableRow: - print( - "from: {}, {} = {}".format( - transportAddress, name.prettyPrint(), val.prettyPrint() - ) - ) - # Stop on EOM - for oid, val in varBindTable[-1]: - if not isinstance(val, pMod.Null): - break - else: - transportDispatcher.jobFinished(1) - - # Generate request for next row - pMod.apiPDU.setVarBinds( - reqPDU, [(x, pMod.null) for x, y in varBindTable[-1]] - ) - pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID()) - transportDispatcher.sendMessage( - encoder.encode(reqMsg), transportDomain, transportAddress - ) - global startedAt - if time() - startedAt > 3: - raise Exception("Request timed out") - startedAt = time() - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, ('demo.pysnmp.com', 161) -) -transportDispatcher.jobStarted(1) - -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py b/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py deleted file mode 100644 index 401ca5264..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py +++ /dev/null @@ -1,123 +0,0 @@ -""" -Spoof IPv4 source address -+++++++++++++++++++++++++ - -Send SNMP GET request from a non-local IP address: - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* from a non-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) -* for OIDs in string form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v2c -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 - -But unlike the above command, this script issues SNMP request from a -non-default, non-local IP address. - -It is indeed possible to originate SNMP traffic from any valid local IP -addresses. It could be a secondary IP interface, for instance. Superuser -privileges are only required to send spoofed packets. Alternatively, -sending from local interface could also be achieved by binding to -it (via openClientMode() parameter). - -Agent would respond to the IP address you used as a source. So this script -could only get a response if that source address is somehow routed to the -host this script is running on. Otherwise it just times out. - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.proto import api -from pyasn1.codec.ber import encoder, decoder -from time import time - -# Send request message to this address -transportAddress = udp.UdpTransportAddress(("127.0.0.1", 161)) - -# Send request message from this non-local (!) IP address -transportAddress.setLocalAddress(("1.2.3.4", 0)) - -# Protocol version to use -# pMod = api.protoModules[api.protoVersion1] -pMod = api.protoModules[api.protoVersion2c] - -# Build PDU -reqPDU = pMod.GetRequestPDU() -pMod.apiPDU.setDefaults(reqPDU) -pMod.apiPDU.setVarBinds( - reqPDU, (("1.3.6.1.2.1.1.1.0", pMod.Null("")), ("1.3.6.1.2.1.1.3.0", pMod.Null(""))) -) - -# Build message -reqMsg = pMod.Message() -pMod.apiMessage.setDefaults(reqMsg) -pMod.apiMessage.setCommunity(reqMsg, "public") -pMod.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -class StopWaiting(Exception): - pass - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise StopWaiting() - - -# noinspection PyUnusedLocal,PyUnusedLocal -def cbRecvFun( - transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus: - print(errorStatus.prettyPrint()) - else: - for oid, val in pMod.apiPDU.getVarBinds(rspPDU): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.jobFinished(1) - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -# Initialize UDP/IPv4 transport -udpSocketTransport = udp.UdpSocketTransport().openClientMode() - -# Use sendmsg()/recvmsg() for socket communication (required for -# IP source spoofing functionality) -udpSocketTransport.enablePktInfo() - -# Enable IP source spoofing (requires root privileges) -udpSocketTransport.enableTransparent() - -transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) - -# Pass message to dispatcher -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, transportAddress -) - -# We might never receive any response as we sent request with fake source IP -transportDispatcher.jobStarted(1) - -# Dispatcher will finish as all jobs counter reaches zero -try: - transportDispatcher.runDispatcher() -except StopWaiting: - transportDispatcher.closeDispatcher() -else: - raise diff --git a/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py b/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py deleted file mode 100644 index 9767946d7..000000000 --- a/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -SET string and integer scalars (SNMPv2c) -++++++++++++++++++++++++++++++++++++++++ - -Perform SNMP SET operation with the following options: - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at demo.pysnmp.com:161 -* for OIDs in string form and values in form of pyasn1 objects - -This script performs similar to the following Net-SNMP command: - -| $ snmpset -v2c -c public -ObentU demo.pysnmp.com 1.3.6.1.2.1.1.9.1.3.1 s 'New description' 1.3.6.1.2.1.1.9.1.4.1 t 12 - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp -from pyasn1.codec.ber import encoder, decoder -from pysnmp.proto import api -from time import time - -# Protocol version to use -# pMod = api.protoModules[api.protoVersion1] -pMod = api.protoModules[api.protoVersion2c] - -# Build PDU -reqPDU = pMod.SetRequestPDU() -pMod.apiPDU.setDefaults(reqPDU) -pMod.apiPDU.setVarBinds( - reqPDU, - # A list of Var-Binds to SET - ( - ("1.3.6.1.2.1.1.9.1.3.1", pMod.OctetString("New system description")), - ("1.3.6.1.2.1.1.9.1.4.1", pMod.TimeTicks(12)), - ), -) - -# Build message -reqMsg = pMod.Message() -pMod.apiMessage.setDefaults(reqMsg) -pMod.apiMessage.setCommunity(reqMsg, "public") -pMod.apiMessage.setPDU(reqMsg, reqPDU) - -startedAt = time() - - -def cbTimerFun(timeNow): - if timeNow - startedAt > 3: - raise Exception("Request timed out") - - -# noinspection PyUnusedLocal,PyUnusedLocal -def cbRecvFun( - transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU -): - while wholeMsg: - rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) - rspPDU = pMod.apiMessage.getPDU(rspMsg) - # Match response to request - if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): - # Check for SNMP errors reported - errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) - if errorStatus: - print(errorStatus.prettyPrint()) - else: - for oid, val in pMod.apiPDU.getVarBinds(rspPDU): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - transportDispatcher.jobFinished(1) - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbRecvFun) -transportDispatcher.registerTimerCbFun(cbTimerFun) - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openClientMode() -) - -# Pass message to dispatcher -transportDispatcher.sendMessage( - encoder.encode(reqMsg), udp.domainName, ('demo.pysnmp.com', 161) -) -transportDispatcher.jobStarted(1) - -# Dispatcher will finish as job#1 counter reaches zero -transportDispatcher.runDispatcher() - -transportDispatcher.closeDispatcher() diff --git a/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py deleted file mode 100644 index aae821e8c..000000000 --- a/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py +++ /dev/null @@ -1,104 +0,0 @@ -""" -Listen for notifications at IPv4 & IPv6 interfaces -++++++++++++++++++++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP messages with the following options: - -* SNMPv1/SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:162 -* over IPv6/UDP, listening at [::1]:162 -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test -| $ snmptrap -v2c -c public udp6:[::1] 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test - -Notification Receiver below uses two different transports for communication -with Notification Originators - UDP over IPv4 and UDP over IPv6. - -"""# -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp, udp6, unix -from pyasn1.codec.ber import decoder -from pysnmp.proto import api - - -# noinspection PyUnusedLocal -def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): - while wholeMsg: - msgVer = int(api.decodeMessageVersion(wholeMsg)) - if msgVer in api.protoModules: - pMod = api.protoModules[msgVer] - else: - print("Unsupported SNMP version %s" % msgVer) - return - reqMsg, wholeMsg = decoder.decode( - wholeMsg, - asn1Spec=pMod.Message(), - ) - print( - "Notification message from {}:{}: ".format( - transportDomain, transportAddress - ) - ) - reqPDU = pMod.apiMessage.getPDU(reqMsg) - if reqPDU.isSameTypeWith(pMod.TrapPDU()): - if msgVer == api.protoVersion1: - print( - "Enterprise: %s" - % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()) - ) - print( - "Agent Address: %s" - % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()) - ) - print( - "Generic Trap: %s" - % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()) - ) - print( - "Specific Trap: %s" - % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()) - ) - print( - "Uptime: %s" % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()) - ) - varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU) - else: - varBinds = pMod.apiPDU.getVarBinds(reqPDU) - print("Var-binds:") - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return wholeMsg - - -transportDispatcher = AsyncoreDispatcher() - -transportDispatcher.registerRecvCbFun(cbFun) - -# UDP/IPv4 -transportDispatcher.registerTransport( - udp.domainName, udp.UdpSocketTransport().openServerMode(("localhost", 162)) -) - -# UDP/IPv6 -transportDispatcher.registerTransport( - udp6.domainName, udp6.Udp6SocketTransport().openServerMode(("::1", 162)) -) - -## Local domain socket -# transportDispatcher.registerTransport( -# unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-manager') -# ) - -transportDispatcher.jobStarted(1) - -try: - # Dispatcher will never finish as job#1 never reaches zero - transportDispatcher.runDispatcher() -except: - transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py b/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py deleted file mode 100644 index ae8cd68f8..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py +++ /dev/null @@ -1,74 +0,0 @@ -""" -Serve non-default MIB tree -++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv3 -* with USM username usr-md5-none -* using alternative set of Managed Objects addressed by - contextEngineId: 8000000001020304, contextName: my-context -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 - -Either of the following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 -n my-context 127.0.0.1 .1.3.6 -| $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 127.0.0.1 .1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.smi import instrum, builder -from pysnmp.proto.api import v2c - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv3/USM setup - -# user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, 3, "usr-md5-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Create an SNMP context with ContextEngineId = 8000000001020304 -snmpContext = context.SnmpContext( - snmpEngine, contextEngineId=v2c.OctetString(hexValue="8000000001020304") -) - -# Create an [empty] set of Managed Objects (MibBuilder), pass it to -# Management Instrumentation Controller and register at SNMP Context -# under ContextName 'my-context' -snmpContext.registerContextName( - v2c.OctetString("my-context"), # Context Name - instrum.MibInstrumController(builder.MibBuilder()), # Managed Objects -) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py b/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py deleted file mode 100644 index dcbde6ea9..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Custom MIB Controller -+++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv3 -* with USM username usr-none-none -* using alternative set of Managed Objects addressed by - contextName: my-context -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 - -The following Net-SNMP command will send GET request to this Agent: - -| $ snmpget -v3 -u usr-none-none -l noAuthNoPriv -n my-context -Ir 127.0.0.1 sysDescr.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.smi import instrum -from pysnmp.proto.api import v2c - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv3/USM setup - -# user: usr-none-none, auth: NONE, priv NONE -config.addV3User(snmpEngine, "usr-none-none") - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, - 3, - "usr-none-none", - "noAuthNoPriv", - (1, 3, 6, 1, 2, 1), - (1, 3, 6, 1, 2, 1), -) - -# Create an SNMP context -snmpContext = context.SnmpContext(snmpEngine) - - -# Very basic Management Instrumentation Controller without -# 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, acInfo=(None, None)): - return [ - (ov[0], v2c.OctetString("You queried OID %s" % ov[0])) for ov in varBinds - ] - - -# Create a custom Management Instrumentation Controller and register at -# SNMP Context under ContextName 'my-context' -snmpContext.registerContextName( - v2c.OctetString("my-context"), # Context Name - EchoMibInstrumController(), # Management Instrumentation -) - -# Register GET&SET Applications at the SNMP engine for a custom SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py b/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py deleted file mode 100644 index 4533bd1ee..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -Specific SNMP Engine ID -+++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv3 -* with SNMP EngineID: 8000000004030201 -* with USM user 'usr-md5-des', auth: MD5, priv DES -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 - -The following Net-SNMP command will walk this Agent: - -| $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000004030201 localhost .1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.proto import rfc1902 - -# Create SNMP engine -snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue="8000000004030201")) - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv3/USM setup - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py b/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py deleted file mode 100644 index 597185c62..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py +++ /dev/null @@ -1,128 +0,0 @@ -""" -Detailed VACM configuration -+++++++++++++++++++++++++++ - -Serves MIB subtrees under different conditions: - -* Respond to SNMPv2c commands -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:161 -* Serve MIB under non-default contextName `abcd` -* Allow access to `SNMPv2-MIB::system` subtree -* Although deny access to `SNMPv2-MIB::sysUpTime` by a bit mask -* Use partial context name matching (`a`) - -This example demonstrates detailed VACM configuration performed via -low-level VACM calls: `addContext`, `addVacmGroup`, `addVacmAccess` -and `addVacmView`. Each function populates one of the tables -defined in `SNMP-VIEW-BASED-ACM-MIB` and used strictly as described -in the above mentioned MIB. - -The following Net-SNMP's commands will GET a value at this Agent: - -| $ snmpget -v2c -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0 - -However this command will fail: - -| $ snmpget -v2c -c public 127.0.0.1 SNMPv2-MIB::sysUpTime.0 - -This command will not reveal `SNMPv2-MIB::sysUpTime.0` among other objects: - -| $ snmpwalk -v2c -c public 127.0.0.1 SNMPv2-MIB::system -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# Register default MIB instrumentation controller with a new SNMP context - -contextName = "abcd" - -snmpContext = context.SnmpContext(snmpEngine) - -snmpContext.registerContextName( - contextName, snmpEngine.msgAndPduDsp.mibInstrumController -) - -# Add new SNMP community name, map it to a new security name and -# SNMP context - -securityName = "my-area" -communityName = "public" - -config.addV1System( - snmpEngine, - securityName, - communityName, - contextEngineId=snmpContext.contextEngineId, - contextName=contextName, -) - -# VACM configuration settings - -securityModel = 2 # SNMPv2c -securityLevel = 1 # noAuthNoPriv - -vacmGroup = "my-group" -readViewName = "my-read-view" - -# We will match by context name prefix -contextPrefix = contextName[:1] - -# Populate SNMP-VIEW-BASED-ACM-MIB::vacmContextTable -config.addContext(snmpEngine, contextName) - -# Populate SNMP-VIEW-BASED-ACM-MIB::vacmSecurityToGroupTable -config.addVacmGroup(snmpEngine, vacmGroup, securityModel, securityName) - -# Populate SNMP-VIEW-BASED-ACM-MIB::vacmAccessTable -config.addVacmAccess( - snmpEngine, - vacmGroup, - contextPrefix, - securityModel, - securityLevel, - "prefix", - readViewName, - "", - "", -) - -# Populate SNMP-VIEW-BASED-ACM-MIB::vacmViewTreeFamilyTable - -# Allow the whole system subtree -config.addVacmView( - snmpEngine, readViewName, "included", "1.3.6.1.2.1.1.1", "1.1.1.1.1.1.1.0" -) - -# ...but exclude one sub-branch (just one scalar OID) -config.addVacmView( - snmpEngine, readViewName, "excluded", "1.3.6.1.2.1.1.3", "1.1.1.1.1.1.1.1" -) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() - -except Exception: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py b/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py deleted file mode 100644 index 246aaa826..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Implementing scalar MIB objects -+++++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv2c -* with SNMP community "public" -* serving custom Managed Object Instance defined within this script -* allow read access only to the subtree where the custom MIB object resides -* over IPv4/UDP, listening at 127.0.0.1:161 - -The following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 - -"""# -import sys -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.proto.api import v2c - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv2c setup - -# SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") - -# Allow read MIB access for this user / securityModels at VACM -config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 5)) - -# Create an SNMP context -snmpContext = context.SnmpContext(snmpEngine) - -# --- create custom Managed Object Instance --- - -mibBuilder = snmpContext.getMibInstrum().getMibBuilder() - -MibScalar, MibScalarInstance = mibBuilder.importSymbols( - "SNMPv2-SMI", "MibScalar", "MibScalarInstance" -) - - -class MyStaticMibScalarInstance(MibScalarInstance): - # noinspection PyUnusedLocal,PyUnusedLocal - def getValue(self, name, idx): - return self.getSyntax().clone( - f"Python {sys.version} running on a {sys.platform} platform" - ) - - -mibBuilder.exportSymbols( - "__MY_MIB", - MibScalar((1, 3, 6, 5, 1), v2c.OctetString()), - MyStaticMibScalarInstance((1, 3, 6, 5, 1), (0,), v2c.OctetString()), -) - -# --- end of Managed Object Instance initialization ---- - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py b/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py deleted file mode 100644 index cef7ded22..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py +++ /dev/null @@ -1,131 +0,0 @@ -""" -Implementing conceptual table -+++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv2c -* with SNMP community "public" -* define a simple SNMP Table within a newly created EXAMPLE-MIB -* pre-populate SNMP Table with a single row of values -* allow read access only to the subtree where example SNMP Table resides -* over IPv4/UDP, listening at 127.0.0.1:161 - -The following Net-SNMP commands will populate and walk a table: - -| $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.2.97.98.99 s "my value" -| $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 4 -| $ snmpwalk -v2c -c public 127.0.0.1 1.3.6 - -...while the following command will destroy the same row - -| $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 6 -| $ snmpwalk -v2c -c public 127.0.0.1 1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.proto.api import v2c - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv2c setup - -# SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") - -# Allow read MIB access for this user / securityModels at VACM -config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 6), (1, 3, 6, 6)) - -# Create an SNMP context -snmpContext = context.SnmpContext(snmpEngine) - -# --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- - -mibBuilder = snmpContext.getMibInstrum().getMibBuilder() - -(MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( - "SNMPv2-SMI", "MibTable", "MibTableRow", "MibTableColumn", "MibScalarInstance" -) - -(RowStatus,) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus") - -mibBuilder.exportSymbols( - "__EXAMPLE-MIB", - # table object - exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess("readcreate"), - # table row object, also carries references to table indices - exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)) - .setMaxAccess("readcreate") - .setIndexNames((0, "__EXAMPLE-MIB", "exampleTableColumn1")), - # table column: string index - exampleTableColumn1=MibTableColumn( - (1, 3, 6, 6, 1, 5, 1), v2c.OctetString() - ).setMaxAccess("readcreate"), - # table column: string value - exampleTableColumn2=MibTableColumn( - (1, 3, 6, 6, 1, 5, 2), v2c.OctetString() - ).setMaxAccess("readcreate"), - # table column: integer value with default - exampleTableColumn3=MibTableColumn( - (1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123) - ).setMaxAccess("readcreate"), - # table column: row status - exampleTableStatus=MibTableColumn( - (1, 3, 6, 6, 1, 5, 4), RowStatus("notExists") - ).setMaxAccess("readcreate"), -) - -# --- end of custom SNMP table definition, empty table now exists --- - -# --- populate custom SNMP table with one row --- - -( - exampleTableEntry, - exampleTableColumn2, - exampleTableColumn3, - exampleTableStatus, -) = mibBuilder.importSymbols( - "__EXAMPLE-MIB", - "exampleTableEntry", - "exampleTableColumn2", - "exampleTableColumn3", - "exampleTableStatus", -) -rowInstanceId = exampleTableEntry.getInstIdFromIndices("example record one") -mibInstrumentation = snmpContext.getMibInstrum() -mibInstrumentation.writeVars( - ( - (exampleTableColumn2.name + rowInstanceId, "my string value"), - (exampleTableColumn3.name + rowInstanceId, 123456), - (exampleTableStatus.name + rowInstanceId, "createAndGo"), - ) -) - -# --- end of SNMP table population --- - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py deleted file mode 100644 index b3ae9cbdf..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py +++ /dev/null @@ -1,66 +0,0 @@ -""" -Serve multiple network transports -+++++++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv2c -* with SNMP community "public" -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 and - over IPv6/UDP, listening at [::1]:161 - -Either of the following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 -| $ snmpwalk -v2c -c public udp6:[::1] .1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp, udp6 - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 at 127.0.0.1:161 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) -# UDP over IPv6 at [::1]:161 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 161)) -) - -# SNMPv2c setup - -# SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") - -# Allow full MIB access for this user / securityModels at VACM -config.addVacmUser( - snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py b/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py deleted file mode 100644 index 3ccd8ff42..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Listen on multiple network interfaces -+++++++++++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv2c -* with SNMP community "public" -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 and 127.0.0.2:161 interfaces - -Either of the following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 -| $ snmpwalk -v2c -c public 127.0.0.2 .1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 at 127.0.0.1:161 -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), -) -# UDP over IPv4 at 127.0.0.2:161 -config.addTransport( - snmpEngine, - udp.domainName + (2,), - udp.UdpTransport().openServerMode(("127.0.0.2", 161)), -) - -# SNMPv2c setup - -# SecurityName <-> CommunityName mapping. -config.addV1System(snmpEngine, "my-area", "public") - -# Allow full MIB access for this user / securityModels at VACM -config.addVacmUser( - snmpEngine, 2, "my-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py b/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py deleted file mode 100644 index 85488541f..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -Running at secondary network interface -++++++++++++++++++++++++++++++++++++++ - -Listen on all local IPv4 interfaces respond to SNMP GET/SET/GETNEXT/GETBULK -queries with the following options: - -* SNMPv3 -* with USM user 'usr-md5-des', auth: MD5, priv DES -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 0.0.0.0:161 -* preserve local IP address when responding (Python 3.3+ required) - -The following Net-SNMP command will walk this Agent: - -| $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 - -In the situation when UDP responder receives a datagram targeted to -a secondary (AKA virtial) IP interface or a non-local IP interface -(e.g. routed through policy routing or iptables TPROXY facility), -OS stack will by default put primary local IP interface address into -the IP source field of the response IP packet. Such datagram may not -reach the sender as either the sender itself or a stateful firewall -somewhere in between would not be able to match response to original -request. - -The following script solves this problem by preserving original request -destination IP address and put it back into response IP packet's source -address field. - -To respond from a non-local (e.g. spoofed) IP address, uncomment the -.enableTransparent() method call and run this script as root. - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# Initialize asyncore-based UDP/IPv4 transport -udpSocketTransport = udp.UdpSocketTransport().openServerMode(("0.0.0.0", 161)) - -# Use sendmsg()/recvmsg() for socket communication (used for preserving -# original destination IP address when responding) -udpSocketTransport.enablePktInfo() - -# Enable IP source spoofing (requires root privileges) -# udpSocketTransport.enableTransparent() - -# Register this transport at SNMP Engine -config.addTransport(snmpEngine, udp.domainName, udpSocketTransport) - -# SNMPv3/USM setup - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.observer.unregisterObserver() - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py deleted file mode 100644 index 2c7f1458d..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py +++ /dev/null @@ -1,70 +0,0 @@ -""" -Multiple SNMP communities -+++++++++++++++++++++++++ - -Respond to SNMP GET/SET/GETNEXT queries with the following options: - -* SNMPv1 -* with SNMP community "public" (read access) or "private" (write access) -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 - -Allow read/write access to all objects in the same MIB subtree. - -The following Net-SNMP's commands will GET/SET a value at this Agent: - -| $ snmpget -v1 -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0 -| $ snmpset -v1 -c private 127.0.0.1 SNMPv2-MIB::sysLocation.0 s "far away" - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv1 setup - -# 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") - -# Allow full MIB access for this user / securityModels at VACM -config.addVacmUser(snmpEngine, 1, "my-read-area", "noAuthNoPriv", (1, 3, 6, 1, 2, 1)) -config.addVacmUser( - snmpEngine, - 1, - "my-write-area", - "noAuthNoPriv", - (1, 3, 6, 1, 2, 1), - (1, 3, 6, 1, 2, 1), -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py deleted file mode 100644 index 9f8db60f0..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -Multiple SNMP Engines -+++++++++++++++++++++ - -Run multiple SNMP Engines each with a complete Command Responder. -Bind each SNMP Engine to a dedicated network transport endpoint: - -* IPv4/UDP, listening at 127.0.0.1:161 -* IPv4/UDP, listening at 127.0.0.2:161 - -Each Command Responder will respond to SNMP GET/SET/GETNEXT/GETBULK -queries with the following options: - -* SNMPv3 -* with USM user 'usr-md5-des', auth: MD5, priv DES -* allow read access to SNMPv2-MIB objects (1.3.6) -* allow write access to SNMPv2-MIB objects (1.3.6.1.2.1) - -The following Net-SNMP commands will walk the first and the second -Agent respectively: - -| $ snmpwalk -Ob -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 127.0.0.1 usmUserEntry -| $ snmpwalk -Ob -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 127.0.0.2 usmUserEntry - -Notice differently configured snmpEngineId's in usmUserEntry columns. - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.proto import rfc1902 -from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher -from pysnmp.carrier.asyncore.dgram import udp - -# Configuration parameters for each of SNMP Engines -snmpEngineInfo = ( - ("0102030405060708", udp.domainName + (0,), ("127.0.0.1", 161)), - ("0807060504030201", udp.domainName + (1,), ("127.0.0.2", 161)), -) - -# Instantiate the single transport dispatcher object -transportDispatcher = AsyncoreDispatcher() - -# Setup a custom data routing function to select snmpEngine by transportDomain -transportDispatcher.registerRoutingCbFun(lambda td, t, d: td) - -# Instantiate and configure SNMP Engines -for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo: - # Create SNMP engine with specific engineID - snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=snmpEngineId)) - - # 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) - - # Transport setup - - # UDP over IPv4 - config.addTransport( - snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) - ) - - # SNMPv3/USM setup - - # user: usr-md5-des, auth: MD5, priv DES - config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", - ) - - # Allow full MIB access for this user / securityModels at VACM - config.addVacmUser( - snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6), (1, 3, 6, 1, 2, 1) - ) - - # Get default SNMP context this SNMP engine serves - snmpContext = context.SnmpContext(snmpEngine) - - # Register SNMP Applications at the SNMP engine for particular SNMP context - cmdrsp.GetCommandResponder(snmpEngine, snmpContext) - cmdrsp.SetCommandResponder(snmpEngine, snmpContext) - cmdrsp.NextCommandResponder(snmpEngine, snmpContext) - cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - transportDispatcher.runDispatcher() -except: - transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py b/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py deleted file mode 100644 index 53e429e68..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py +++ /dev/null @@ -1,87 +0,0 @@ -""" -Multiple SNMP USM users -+++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv3 -* with USM user 'usr-md5-des', auth: MD5, priv DES or - with USM user 'usr-sha-none', auth: SHA, no privacy - with USM user 'usr-sha-aes128', auth: SHA, priv AES -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 - -Either of the following Net-SNMP commands will walk this Agent: - -| $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 -| $ snmpwalk -v3 -u usr-sha-none -l authNoPriv -a SHA -A authkey1 localhost .1.3.6 -| $ snmpwalk -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 localhost .1.3.6 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 1161)) -) - -# SNMPv3/USM setup - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) -# user: usr-sha-none, auth: SHA, priv NONE -config.addV3User(snmpEngine, "usr-sha-none", config.usmHMACSHAAuthProtocol, "authkey1") -# user: usr-sha-none, auth: SHA, priv AES -config.addV3User( - snmpEngine, - "usr-sha-aes128", - config.usmHMACSHAAuthProtocol, - "authkey1", - config.usmAesCfb128Protocol, - "privkey1", -) - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) -config.addVacmUser( - snmpEngine, 3, "usr-sha-none", "authNoPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) -config.addVacmUser( - snmpEngine, 3, "usr-sha-aes128", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py b/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py deleted file mode 100644 index 09f6b904c..000000000 --- a/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py +++ /dev/null @@ -1,102 +0,0 @@ -""" -Observe SNMP engine operations -++++++++++++++++++++++++++++++ - -Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with -the following options: - -* SNMPv3 -* with USM user 'usr-md5-des', auth: MD5, priv DES or -* allow access to SNMPv2-MIB objects (1.3.6.1.2.1) -* over IPv4/UDP, listening at 127.0.0.1:161 -* registers its own execution observer to snmpEngine - -The following Net-SNMP command will walk this Agent: - -| $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 - -This script will report some details on request processing as seen -by rfc3412.receiveMessage() and rfc3412.returnResponsePdu() -abstract interfaces. - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, context -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine -snmpEngine = engine.SnmpEngine() - - -# Execution point observer setup - -# Register a callback to be invoked at specified execution point of -# SNMP Engine and passed local variables at code point's local scope -# noinspection PyUnusedLocal,PyUnusedLocal -def requestObserver(snmpEngine, execpoint, variables, cbCtx): - print("Execution point: %s" % execpoint) - print( - "* transportDomain: %s" - % ".".join([str(x) for x in variables["transportDomain"]]) - ) - print( - "* transportAddress: {} (local {})".format( - "@".join([str(x) for x in variables["transportAddress"]]), - "@".join([str(x) for x in variables["transportAddress"].getLocalAddress()]), - ) - ) - print("* securityModel: %s" % variables["securityModel"]) - print("* securityName: %s" % variables["securityName"]) - print("* securityLevel: %s" % variables["securityLevel"]) - print("* contextEngineId: %s" % variables["contextEngineId"].prettyPrint()) - print("* contextName: %s" % variables["contextName"].prettyPrint()) - print("* PDU: %s" % variables["pdu"].prettyPrint()) - - -snmpEngine.observer.registerObserver( - requestObserver, "rfc3412.receiveMessage:request", "rfc3412.returnResponsePdu" -) - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 161)) -) - -# SNMPv3/USM setup - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) - -# Allow full MIB access for each user at VACM -config.addVacmUser( - snmpEngine, 3, "usr-md5-des", "authPriv", (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1) -) - -# Get default SNMP context this SNMP engine serves -snmpContext = context.SnmpContext(snmpEngine) - -# Register SNMP Applications at the SNMP engine for particular SNMP context -cmdrsp.GetCommandResponder(snmpEngine, snmpContext) -cmdrsp.SetCommandResponder(snmpEngine, snmpContext) -cmdrsp.NextCommandResponder(snmpEngine, snmpContext) -cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) - -# Register an imaginary never-ending job to keep I/O dispatcher running forever -snmpEngine.transportDispatcher.jobStarted(1) - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.observer.unregisterObserver() - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py b/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py deleted file mode 100644 index 96aad37f2..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py +++ /dev/null @@ -1,130 +0,0 @@ -""" -Notification over multiple SNMP versions -++++++++++++++++++++++++++++++++++++++++ - -Send SNMP INFORM notifications to multiple Managers using different -security settings: - -* SNMPv2c -* with community name 'public' -* AND -* SNMPv3 -* with user 'usr-md5-none', auth: MD5, priv NONE -* over IPv4/UDP -* send INFORM notification -* to multiple Managers at 127.0.0.1:162, 127.0.0.1:162 -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - -Functionally similar to: - -| $ snmpinform -v3 -l authPriv -u usr-md5-none -A authkey1 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' -| $ snmpinform -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SNMPv2c: - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds-1", "my-area", "noAuthNoPriv", 1) - -# SNMPv3: - -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") -config.addTargetParams(snmpEngine, "my-creds-2", "usr-md5-none", "authNoPriv") - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -# First target -config.addTargetAddr( - snmpEngine, - "my-nms-1", - udp.domainName, - ("127.0.0.1", 162), - "my-creds-1", - tagList="all-my-managers", -) -# Second target -config.addTargetAddr( - snmpEngine, - "my-nms-2", - udp.domainName, - ("127.0.0.1", 162), - "my-creds-2", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "inform" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - - -# Error/confirmation receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - print( - "Notification {}, status - {}".format( - sendRequestHandle, errorIndication and errorIndication or "delivered" - ) - ) - - -# Build and submit notification message to dispatcher -sendRequestHandle = ntfOrg.sendVarBinds( - snmpEngine, - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ], - cbFun, -) - -print("Notifications %s are scheduled to be sent" % sendRequestHandle) - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py b/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py deleted file mode 100644 index 0981e8495..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py +++ /dev/null @@ -1,102 +0,0 @@ -""" -Send crafted TRAP PDU -+++++++++++++++++++++ - -Initialize TRAP PDU and pass it over to unified SNMPv3 message processing -framework for further treatment. - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send TRAP notification -* initialize TRAP PDU with the following var-binds: - 1.3.6.1.2.1.1.3.0 = 123 - 1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.6.3.1.1.5.1 - -Functionally similar to: - -| $ snmptrap -v2c -c public demo.pysnmp.com 0 1.3.6.1.6.3.1.1.5.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) - -# Create named target -config.addTargetAddr( - snmpEngine, "my-nms", udp.domainName, ("127.0.0.1", 162), "my-creds" -) - -# *** SNMP engine configuration is complete by this line *** - -# Create SNMP v2c TRAP PDU with defaults -trapPDU = v2c.TrapPDU() -v2c.apiTrapPDU.setDefaults(trapPDU) - -# Set custom var-binds to TRAP PDU -v2c.apiTrapPDU.setVarBinds( - trapPDU, - [ - # sysUpTime - (v2c.ObjectIdentifier("1.3.6.1.2.1.1.3.0"), v2c.TimeTicks(123)), - # snmpTrapPDU - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - ], -) - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - - -# Error/confirmation receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - print( - "Notification {}, status - {}".format( - sendRequestHandle, errorIndication and errorIndication or "delivered" - ) - ) - - -# Build and submit notification message to dispatcher -ntfOrg.sendPdu( - snmpEngine, - # Notification targets - "my-nms", # target address - None, - "", # contextEngineId, contextName - trapPDU, - cbFun, -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py b/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py deleted file mode 100644 index 5ad5c71db..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -Notification to multiple addresses -++++++++++++++++++++++++++++++++++ - -Send SNMP TRAP notifications to multiple Managers using different -security settings: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send TRAP notification -* to multiple Managers at 127.0.0.1:162, 127.0.0.1:162 -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - 1.3.6.1.2.1.1.5.0 = 'Notificator Example' - -Functionally similar to: - -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -# First target -config.addTargetAddr( - snmpEngine, - "my-nms-1", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) -# Second target -config.addTargetAddr( - snmpEngine, - "my-nms-2", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) -# Third target -config.addTargetAddr( - snmpEngine, - "my-nms-3", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], -) - -print("Notifications are scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py b/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py deleted file mode 100644 index 77bee973c..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py +++ /dev/null @@ -1,107 +0,0 @@ -""" -Notification over multiple network protocols -++++++++++++++++++++++++++++++++++++++++++++ - -Send SNMP INFORM notifications to multiple Managers over different -network protocols: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP and UDP/IPv6 -* send TRAP notification -* to two Managers through different network transports -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - 1.3.6.1.2.1.1.5.0 = 'Notificator Example' - -Functionally similar to: - -| $ snmptrap -v2c -c public udp:127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' -| $ snmptrap -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp, udp6 -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoints and bind it with security settings yielding -# a target name: - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms-1", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# UDP/IPv6 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms-2", - udp6.domainName, - ("::1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py b/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py deleted file mode 100644 index 6ef036862..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py +++ /dev/null @@ -1,87 +0,0 @@ -""" -Send packet from specific network interface/port -++++++++++++++++++++++++++++++++++++++++++++++++ - -Send SNMP notification using the following options: - -* SNMPv1 -* with community name 'public' -* over IPv4/UDP -* to a Manager at 127.0.0.1 UDP port 162 -* from local address 0.0.0.0, UDP port 61024 -* send TRAP notification -* with TRAP ID 'coldStart' specified as an OID - -Functionally similar to: - -| $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.6.3.1.1.5.1 0.0.0.0 1 0 0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv1 -> 0) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# 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( - snmpEngine, - udp.domainName, - udp.UdpSocketTransport().openClientMode(iface=("0.0.0.0", 61024)), -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ) - ], -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and stop -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py b/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py deleted file mode 100644 index 02bc4fd81..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -Notification to multiple SNMP managers -++++++++++++++++++++++++++++++++++++++ - -Send SNMP TRAP notifications to multiple Managers using the -following options: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send TRAP notification -* to multiple Managers at 127.0.0.1:162, 127.0.0.1:162 -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - 1.3.6.1.2.1.1.5.0 = 'Notificator Example' - -Functionally similar to: - -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -# First target -config.addTargetAddr( - snmpEngine, - "my-nms-1", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) -# Second target -config.addTargetAddr( - snmpEngine, - "my-nms-2", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) -# Third target -config.addTargetAddr( - snmpEngine, - "my-nms-3", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM) -# to what targets (chosen by tag) and with what credentials. -config.addNotificationTarget( - 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], -) - -print("Notifications are scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py b/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py deleted file mode 100644 index 4583023a9..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py +++ /dev/null @@ -1,102 +0,0 @@ -""" -SNMPv3 INFORM, auth: MD5, privacy: none -+++++++++++++++++++++++++++++++++++++++ - -Send SNMP INFORM notification using the following options: - -* SNMPv3 -* with user 'usr-md5-none', auth: MD5, priv NONE -* over IPv4/UDP -* to a Manager at demo.pysnmp.com:162 -* send INFORM notification -* with TRAP ID 'warmStart' specified as an OID -* include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' - -Functionally similar to: - -| $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.pysnmp.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# Add USM user -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - - -# Error/confirmation receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - print( - "Notification {}, status - {}".format( - sendRequestHandle, errorIndication and errorIndication or "delivered" - ) - ) - - -# Build and submit notification message to dispatcher -sendRequestHandle = ntfOrg.sendVarBinds( - snmpEngine, - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds: SNMPv2-MIB::coldStart, ... - [ - ( - (1, 3, 6, 1, 6, 3, 1, 1, 5, 1), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("system name")), - ], - cbFun, -) - -print("Notification %s scheduled to be sent" % sendRequestHandle) - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/v1-trap.py b/examples/v3arch/asyncore/agent/ntforg/v1-trap.py deleted file mode 100644 index eccb41a60..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/v1-trap.py +++ /dev/null @@ -1,101 +0,0 @@ -""" -SNMPv1 TRAP -+++++++++++ - -Send SNMP notification using the following options: - -* SNMPv1 -* with community name 'public' -* over IPv4/UDP -* to a Manager at 127.0.0.1:162 -* send TRAP notification -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: -* overriding Uptime value with 12345 -* overriding Agent Address with '127.0.0.1' -* overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 -* include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' - -Functionally similar to: - -| $ snmptrap -v1 -c public demo.pysnmp.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system" - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv1 -> 0) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # Uptime value with 12345 - (v2c.ObjectIdentifier("1.3.6.1.2.1.1.3.0"), v2c.TimeTicks(12345)), - # trap OID: Generic Trap #6 (enterpriseSpecific) - # and Specific Trap 432 - ( - v2c.ObjectIdentifier("1.3.6.1.6.3.1.1.5.1"), - v2c.ObjectIdentifier("1.3.6.1.4.1.20408.4.1.1.2.0.432"), - ), - # Agent Address with '127.0.0.1' - (v2c.ObjectIdentifier("1.3.6.1.6.3.18.1.3.0"), v2c.IpAddress("127.0.0.1")), - # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 - ( - v2c.ObjectIdentifier("1.3.6.1.6.3.1.1.4.3.0"), - v2c.ObjectIdentifier("1.3.6.1.4.1.20408.4.1.1.2"), - ), - # managed object '1.3.6.1.2.1.1.1.0' = 'my system' - (v2c.ObjectIdentifier("1.3.6.1.2.1.1.1.0"), v2c.OctetString("my system")), - ], -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and stop -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py b/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py deleted file mode 100644 index dae16c434..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -INFORM notification -+++++++++++++++++++ - -Send SNMP INFORM notification using the following options: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send INFORM notification -* to a Manager at 127.0.0.1:162 -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - 1.3.6.1.2.1.1.5.0 = 'Notificator Example' - -Functionally similar to: - -| $ snmpinform -v2c -c public 127.0.0.1 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example Notificator' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping (+ transport binding) -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - - -# Error/confirmation receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - print( - "Notification {}, status - {}".format( - sendRequestHandle, errorIndication and errorIndication or "delivered" - ) - ) - - -# Build and submit notification message to dispatcher -sendRequestHandle = ntfOrg.sendVarBinds( - snmpEngine, - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], - cbFun, -) - -print("Notification %s scheduled to be sent" % sendRequestHandle) - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py b/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py deleted file mode 100644 index 893647f56..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Sending notification with OBJECT's -++++++++++++++++++++++++++++++++++ - -Send SNMP TRAP notification using the following options: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send TRAP notification -* to a Manager at 127.0.0.1:162 -* with TRAP ID IF-MIB::ifLink as MIB symbol - -The IF-MIB::ifLink NOTIFICATION-TYPE implies including four other -var-binds into the notification message describing the incident -occurred. These var-binds are: -IF-MIB::ifIndex."x" -IF-MIB::ifAdminStatus."x" -IF-MIB::ifOperStatus."x" -IF-MIB::ifDescr."x" - -Where "x" is MIB table index (instance index). - -Functionally similar to: - -| $ snmptrap -v2c -c public 127.0.0.1 0 1.3.6.1.6.3.1.1.5.3 IF-MIB::ifIndex."1" IF-MIB::ifAdminStatus."1" IF-MIB::ifOperStatus."1" IF-MIB::ifDescr."1" - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.smi import rfc1902, view - -# -# Here we fill in some values for Managed Objects Instances (invoked -# later while building TRAP message) by NOTIFICATION-TYPE macro evaluation. -# In real Agent app, these values should already be initialized during -# Agent runtime. -# -instanceIndex = (1,) -objects = { - ("IF-MIB", "ifIndex"): instanceIndex[0], - ("IF-MIB", "ifAdminStatus"): "up", - ("IF-MIB", "ifOperStatus"): "down", - ("IF-MIB", "ifDescr"): "eth0", -} - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# MIB view controller is used for MIB lookup purposes -mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoints and bind it with security settings yielding -# a target name: - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms-1", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - rfc1902.NotificationType( - rfc1902.ObjectIdentity("IF-MIB", "linkUp"), - instanceIndex=instanceIndex, - objects=objects, - ).resolveWithMib(mibViewController), -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py b/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py deleted file mode 100644 index 6280a9bef..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py +++ /dev/null @@ -1,110 +0,0 @@ -""" -SNMPv2c TRAP -++++++++++++ - -Send SNMP TRAP notification using the following options: - -* SNMPv2c -* with community name 'public' -* over IPv4/UDP -* send TRAP notification -* to a Manager at 127.0.0.1:162 -* with TRAP ID 'coldStart' specified as an OID -* include managed objects information: - 1.3.6.1.2.1.1.1.0 = 'Example Notificator' - 1.3.6.1.2.1.1.5.0 = 'Notificator Example' - -Functionally similar to: - -| $ snmptrap -v2c -c public 127.0.0.1 12345 1.3.6.1.4.1.20408.4.1.1.2 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public", transportTag="all-my-managers") - -# Specify security settings per SecurityName (SNMPv2c -> 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - - -# Error/confirmation receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - print( - "Notification {}, status - {}".format( - sendRequestHandle, errorIndication and errorIndication or "delivered" - ) - ) - - -# Build and submit notification message to dispatcher -sendRequestHandle = ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString("Example Notificator")), - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], - cbFun, -) - -print("Notification %s is scheduled to be sent" % sendRequestHandle) - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/agent/ntforg/v3-trap.py b/examples/v3arch/asyncore/agent/ntforg/v3-trap.py deleted file mode 100644 index 376e1aa7b..000000000 --- a/examples/v3arch/asyncore/agent/ntforg/v3-trap.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -SNMPv3 TRAP, auth: MD5, privacy: DES -++++++++++++++++++++++++++++++++++++ - -Send SNMP TRAP notification using the following options: - -* SNMPv3 -* with user 'usr-md5-des', auth: MD5, priv DES -* over IPv4/UDP -* send TRAP notification -* to a Manager at 127.0.0.1:162 -* with TRAP ID 'warmStart' specified as an OID -* include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' - -Functionally similar to: - -| $ snmptrap -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -e 8000000001020304 demo.pysnmp.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s "my system" - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntforg -from pysnmp.proto.api import v2c - -# Create SNMP engine instance with specific (and locally unique) -# SnmpEngineId -- it must also be known to the receiving party -# and configured at its VACM users table. -snmpEngine = engine.SnmpEngine( - snmpEngineID=v2c.OctetString(hexValue="8000000001020304") -) - -# Add USM user -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv") - -# Setup transport endpoint and bind it with security settings yielding -# a target name -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-nms", - udp.domainName, - ("127.0.0.1", 162), - "my-creds", - tagList="all-my-managers", -) - -# Specify what kind of notification should be sent (TRAP or INFORM), -# to what targets (chosen by tag) and what filter should apply to -# the set of targets (selected by tag) -config.addNotificationTarget( - snmpEngine, "my-notification", "my-filter", "all-my-managers", "trap" -) - -# 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)) - -# *** SNMP engine configuration is complete by this line *** - -# Create Notification Originator App instance. -ntfOrg = ntforg.NotificationOriginator() - -# Build and submit notification message to dispatcher -ntfOrg.sendVarBinds( - snmpEngine, - # Notification targets - "my-notification", # notification targets - None, - "", # contextEngineId, contextName - # var-binds - [ - # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart - ( - (1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), - v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)), - ), - # additional var-binds: ( (oid, value), ... ) - ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString("Notificator Example")), - ], -) - -print("Notification is scheduled to be sent") - -# Run I/O dispatcher which would send pending message and process response -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py b/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py deleted file mode 100644 index ad37d5eba..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py +++ /dev/null @@ -1,88 +0,0 @@ -""" -Custom ContextEngineId and ContextName -++++++++++++++++++++++++++++++++++++++ - -Send a SNMP GET request with the following options: - -* with SNMPv3 with user 'usr-md5-none', SHA auth and no privacy protocols -* for MIB instance identified by -* contextEngineId: 0x80004fb805636c6f75644dab22cc, -* contextName: da761cfc8c94d3aceef4f60f049105ba -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -E 80004fb805636c6f75644dab22cc -n da761cfc8c94d3aceef4f60f049105ba -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.proto import rfc1902 - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-md5-none, auth: MD5, priv: NONE -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message, pass custom ContextEngineId & ContextName -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - # contextEngineId - rfc1902.OctetString(hexValue="80004fb805636c6f75644dab22cc"), - # contextName - rfc1902.OctetString("da761cfc8c94d3aceef4f60f049105ba"), - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py b/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py deleted file mode 100644 index 06a1a1bbb..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -SNMPv2c, custom timeout -+++++++++++++++++++++++ - -Send a SNMP GET request: - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* wait 3 seconds for response, retry 5 times (plus one initial attempt) -* for an OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v2c -c public -ObentU -r 5 -t 1 127.0.0.1 1.3.6.1.2.1.1.1.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv2c setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, - "my-router", - udp.domainName, - ("127.0.0.1", 161), - "my-creds", - timeout=300, # in 1/100 sec - retryCount=5, -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py b/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py deleted file mode 100644 index cd87ad38f..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Walk Agent over IPv6 -++++++++++++++++++++ - -Send a series of SNMP GETNEXT requests with the following options: - -* with SNMPv3 with user 'usr-md5-none', MD5 auth and no privacy protocols -* over IPv6/UDP -* to an Agent at [::1]:161 -* for two OIDs in tuple form -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v3 -l authNoPriv -u usr-md5-none -A authkey1 -ObentU udp6:[::1]:161 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp6 -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-md5-des, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-none", "authNoPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv6 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode() -) -config.addTargetAddr(snmpEngine, "my-router", udp6.domainName, ("::1", 161), "my-creds") - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return - if errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return True # signal dispatcher to continue - - -# Prepare initial request to be sent -cmdgen.NextCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py deleted file mode 100644 index 06bbd3417..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -Fetch scalar and table variables -++++++++++++++++++++++++++++++++ - -Send a series of SNMP GETBULK requests with the following options: - -* with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* with values non-repeaters = 1, max-repetitions = 25 -* for two OIDs in tuple form (first OID is non-repeating) -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpbulkwalk -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -C n1 -C r25 -ObentU 127.0.0.1 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) -config.addTargetParams(snmpEngine, "my-creds", "usr-md5-des", "authPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequesthandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return # stop on error - if errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return True # signal dispatcher to continue walking - - -# Prepare initial request to be sent -cmdgen.BulkCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - 0, - 25, # non-repeaters, max-repetitions - (((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)), - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py deleted file mode 100644 index 9b3327ef4..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py +++ /dev/null @@ -1,90 +0,0 @@ -""" -Bulk walk MIB -+++++++++++++ - -Send a series of SNMP GETBULK requests -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* with values non-repeaters = 0, max-repetitions = 25 -* for two OIDs in tuple form -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpbulkwalk -v2c -c public -C n0 -C r25 -ObentU 127.0.0.1 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.carrier.asyncore.dgram import udp - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv2c setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequesthandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return # stop on error - if errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return True # signal dispatcher to continue walking - - -# Prepare initial request to be sent -cmdgen.BulkCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - 0, - 25, # non-repeaters, max-repetitions - [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py deleted file mode 100644 index 6cddc992a..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -Walk Agent and resolve variables at MIB -+++++++++++++++++++++++++++++++++++++++ - -Send a series of SNMP GETNEXT requests with the following options: - -* with SNMPv1, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for two OIDs in tuple form -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v1 -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.smi import compiler, view, rfc1902 - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# Attach MIB compiler to SNMP Engine (MIB Builder) -# This call will fail if PySMI is not present on the system -compiler.addMibCompiler(snmpEngine.getMibBuilder()) -# ... 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()) - -# -# -# SNMPv1/2c setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return - # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, - # so we ignore noSuchName error here - if errorStatus and errorStatus != 2: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for varBind in varBindRow: - print( - rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1]) - .resolveWithMib(mibViewController) - .prettyPrint() - ) - return 1 # signal dispatcher to continue - - -# Prepare initial request to be sent -cmdgen.NextCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [ - rfc1902.ObjectType(rfc1902.ObjectIdentity("iso.org.dod")).resolveWithMib( - mibViewController - ), - rfc1902.ObjectType(rfc1902.ObjectIdentity("IF-MIB", "ifMIB")).resolveWithMib( - mibViewController - ), - ], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py deleted file mode 100644 index 563c47fe2..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py +++ /dev/null @@ -1,90 +0,0 @@ -""" -Fetch two subtrees in parallel -++++++++++++++++++++++++++++++ - -Send a series of SNMP GETNEXT requests with the following options: - -* with SNMPv1, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for two OIDs in tuple form -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v1 -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv1/2c setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return - # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, - # so we ignore noSuchName error here - if errorStatus and errorStatus != 2: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return 1 # signal dispatcher to continue - - -# Prepare initial request to be sent -cmdgen.NextCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py b/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py deleted file mode 100644 index d0f5f0706..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py +++ /dev/null @@ -1,129 +0,0 @@ -""" -Report SNMP engine processing details -+++++++++++++++++++++++++++++++++++++ - -Send SNMP GET request with the following options: - -* with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form -* also registers its own execution observer to snmpEngine - -While execution, this script will report some details on request processing -as seen by rfc3412.sendPdu() and rfc3412.receiveMessage() abstract interfaces. - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - - -# Execution point observer setup - -# Register a callback to be invoked at specified execution point of -# SNMP Engine and passed local variables at code point's local scope -# noinspection PyUnusedLocal,PyUnusedLocal -def requestObserver(snmpEngine, execpoint, variables, cbCtx): - print("Execution point: %s" % execpoint) - print( - "* transportDomain: %s" - % ".".join([str(x) for x in variables["transportDomain"]]) - ) - print( - "* transportAddress: %s" - % "@".join([str(x) for x in variables["transportAddress"]]) - ) - print("* securityModel: %s" % variables["securityModel"]) - print("* securityName: %s" % variables["securityName"]) - print("* securityLevel: %s" % variables["securityLevel"]) - print( - "* contextEngineId: {}".format( - variables["contextEngineId"] - and variables["contextEngineId"].prettyPrint() - or "" - ) - ) - print("* contextName: %s" % variables["contextName"].prettyPrint()) - print("* PDU: %s" % variables["pdu"].prettyPrint()) - - -snmpEngine.observer.registerObserver( - requestObserver, "rfc3412.sendPdu", "rfc3412.receiveMessage:response" -) - -# -# SNMPv3/USM setup -# - -# user: usr-sha-aes, auth: SHA, priv AES -config.addV3User( - snmpEngine, - "usr-sha-aes", - config.usmHMACSHAAuthProtocol, - "authkey1", - config.usmAesCfb128Protocol, - "privkey1", -) -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() - -snmpEngine.observer.unregisterObserver() diff --git a/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py b/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py deleted file mode 100644 index 9cbe6a5d5..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py +++ /dev/null @@ -1,95 +0,0 @@ -""" -Pull MIB subtree -++++++++++++++++ - -Send a series of SNMP GETNEXT requests -* with SNMPv3 with user 'usr-none-none', no auth and no privacy protocols -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in string form -* stop whenever received OID goes out of initial prefix (it may be a table) - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v3 -l noAuthNoPriv -u usr-none-none -ObentU 127.0.0.1:161 1.3.6.1.2.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.proto import rfc1902 - -# Initial OID prefix -initialOID = rfc1902.ObjectName("1.3.6.1.2.1.1") - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-none-none, auth: none, priv: none -config.addV3User( - snmpEngine, - "usr-none-none", -) -config.addTargetParams(snmpEngine, "my-creds", "usr-none-none", "noAuthNoPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return - if errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - if initialOID.isPrefixOf(oid): - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - else: - return False # signal dispatcher to stop - return True # signal dispatcher to continue - - -# Prepare initial request to be sent -cmdgen.NextCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [(initialOID, None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py b/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py deleted file mode 100644 index 07a36a403..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Send packets from specific local interface -++++++++++++++++++++++++++++++++++++++++++ - -Send a series of SNMP GETNEXT requests with the following options: - -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* sending packets from primary local interface 0.0.0.0, local port 61024 -* for two OIDs in tuple form -* stop on end-of-mib condition for both OIDs - -This script performs similar to the following Net-SNMP command: - -| $ snmpwalk -v2c -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1 1.3.6.1.4.1.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv1/2c setup (if you use SNMPv1 or v2c) -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, - udp.domainName, - udp.UdpSocketTransport().openClientMode(("0.0.0.0", 61024)), -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBindTable, - cbCtx, -): - if errorIndication: - print(errorIndication) - return - if errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or "?", - ) - ) - return # stop on error - for varBindRow in varBindTable: - for oid, val in varBindRow: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - return 1 # signal dispatcher to continue - - -# Prepare initial request to be sent -cmdgen.NextCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 2, 1, 11), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py b/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py deleted file mode 100644 index cf8ff0aaa..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py +++ /dev/null @@ -1,90 +0,0 @@ -""" -SET string and integer scalars -++++++++++++++++++++++++++++++ - -Send SNMP SET request with the following options: - -* with SNMPv1 with community name 'private' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for OIDs in tuple form and an integer and string-typed values - -This script performs similar to the following Net-SNMP command: - -| $ snmpset -v1 -c private -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.9.1.3.1 s 'my value' 1.3.6.1.2.1.1.9.1.4.1 t 123 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.proto import rfc1902 - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv1 setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "private") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, - # so we ignore noSuchName error here - elif errorStatus and errorStatus != 2: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.SetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [ - ((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString("my value")), - ((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123)), - ], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py b/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py deleted file mode 100644 index f3586b647..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py +++ /dev/null @@ -1,110 +0,0 @@ -""" -Spoof source address -++++++++++++++++++++ - -Send a SNMP GET request -* with SNMPv2c, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* from a non-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) -* for an OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v2c -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1.1.0 - -But unlike the above command, this script issues SNMP request from -a non-default, non-local IP address. - -It is indeed possible to originate SNMP traffic from any valid local -IP addresses. It could be a secondary IP interface, for instance. -Superuser privileges are only required to send spoofed packets. -Alternatively, sending from local interface could also be achieved by -binding to it (via openClientMode() parameter). - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv1 setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# Initialize asyncore-based UDP/IPv4 transport -udpSocketTransport = udp.UdpSocketTransport().openClientMode() - -# Use sendmsg()/recvmsg() for socket communication (required for -# IP source spoofing functionality) -udpSocketTransport.enablePktInfo() - -# Enable IP source spoofing (requires root privileges) -udpSocketTransport.enableTransparent() - -# Register this transport at SNMP Engine -config.addTransport(snmpEngine, udp.domainName, udpSocketTransport) - -# Configure destination IPv4 address as well as source IPv4 address -config.addTargetAddr( - snmpEngine, - "my-router", - udp.domainName, - ("127.0.0.1", 161), - "my-creds", - sourceAddress=("1.2.3.4", 0), -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, - # so we ignore noSuchName error here - elif errorStatus and errorStatus != 2: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py deleted file mode 100644 index 218623722..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py +++ /dev/null @@ -1,90 +0,0 @@ -""" -SNMPv3, auth: SHA, privacy: AES128 -++++++++++++++++++++++++++++++++++ - -Send a SNMP GET request -* with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-sha-aes, auth: SHA, priv AES -config.addV3User( - snmpEngine, - "usr-sha-aes", - config.usmHMACSHAAuthProtocol, - "authkey1", - config.usmAesCfb128Protocol, - "privkey1", -) -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-aes", "authPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() - -config.delTransport(snmpEngine, udp.domainName).closeTransport() diff --git a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py b/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py deleted file mode 100644 index 7769069d9..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Set string value -++++++++++++++++ - -Send a SNMP SET request with the following options: - -* with SNMPv3 with user 'usr-sha-none', SHA auth and no privacy protocols -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form and a string-typed value - -This script performs similar to the following Net-SNMP command: - -| $ snmpset -v3 -l authNoPriv -u usr-sha-none -a SHA -A authkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.9.1.3.1 s 'my new value' - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.proto import rfc1902 - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv3/USM setup -# - -# user: usr-sha-none, auth: SHA, priv none -config.addV3User(snmpEngine, "usr-sha-none", config.usmHMACSHAAuthProtocol, "authkey1") -config.addTargetParams(snmpEngine, "my-creds", "usr-sha-none", "authNoPriv") - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.SetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString("my new value"))], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/v1-get.py b/examples/v3arch/asyncore/manager/cmdgen/v1-get.py deleted file mode 100644 index ec086a2c2..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/v1-get.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -SNMPv1 -++++++ - -* with SNMPv1, community 'public' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form - -This script performs similar to the following Net-SNMP command: - -| $ snmpget -v1 -c public -ObentU 127.0.0.1 1.3.6.1.2.1.1.1.0 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv1 setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 0) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, - # so we ignore noSuchName error here - elif errorStatus and errorStatus != 2: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.GetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py b/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py deleted file mode 100644 index ca68903ef..000000000 --- a/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Set scalar value -++++++++++++++++ - -Send a SNMP SET request -* with SNMPv2c with community name 'private' -* over IPv4/UDP -* to an Agent at 127.0.0.1:161 -* for an OID in tuple form and an integer-typed value - -This script performs similar to the following Net-SNMP command: - -| $ snmpset -v2c -c private -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.9.1.4.1 t 123 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import cmdgen -from pysnmp.proto import rfc1902 - -# Create SNMP engine instance -snmpEngine = engine.SnmpEngine() - -# -# SNMPv2c setup -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "private") - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "my-creds", "my-area", "noAuthNoPriv", 1) - -# -# Setup transport endpoint and bind it with security settings yielding -# a target name -# - -# UDP/IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() -) -config.addTargetAddr( - snmpEngine, "my-router", udp.domainName, ("127.0.0.1", 161), "my-creds" -) - - -# Error/response receiver -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun( - snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx, -): - if errorIndication: - print(errorIndication) - elif errorStatus: - print( - "{} at {}".format( - errorStatus.prettyPrint(), - errorIndex and varBinds[int(errorIndex) - 1][0] or "?", - ) - ) - else: - for oid, val in varBinds: - print(f"{oid.prettyPrint()} = {val.prettyPrint()}") - - -# Prepare and send a request message -cmdgen.SetCommandGenerator().sendVarBinds( - snmpEngine, - "my-router", - None, - "", # contextEngineId, contextName - [((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))], - cbFun, -) - -# Run I/O dispatcher which would send pending queries and process responses -snmpEngine.transportDispatcher.runDispatcher() diff --git a/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py b/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py deleted file mode 100644 index 1fc950840..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Receive notifications noting peer address -+++++++++++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv1/SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:162 -* use observer facility to pull lower-level request details from SNMP engine -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntfrcv - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4, first listening interface/port -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 162)), -) - -# SNMPv1/2c setup - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - # Get an execution context... - execContext = snmpEngine.observer.getExecutionContext( - "rfc3412.receiveMessage:request" - ) - - # ... and use inner SNMP engine data to figure out peer address - print( - 'Notification from {}, ContextEngineId "{}", ContextName "{}"'.format( - "@".join([str(x) for x in execContext["transportAddress"]]), - contextEngineId.prettyPrint(), - contextName.prettyPrint(), - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py deleted file mode 100644 index 0a03ad2fb..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Serving multiple network interfaces -+++++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv1/SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:162 - over IPv4/UDP, listening at 127.0.0.1:2162 -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test -| $ snmpinform -v2c -c public 127.0.0.1:2162 123 1.3.6.1.6.3.1.1.5.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntfrcv - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4, first listening interface/port -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 162)), -) - -# UDP over IPv4, second listening interface/port -config.addTransport( - snmpEngine, - udp.domainName + (2,), - udp.UdpTransport().openServerMode(("127.0.0.1", 2162)), -) - -# SNMPv1/2c setup - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - print( - 'Notification from ContextEngineId "{}", ContextName "{}"'.format( - contextEngineId.prettyPrint(), contextName.prettyPrint() - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py deleted file mode 100644 index 970d6444c..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Using multiple network transports -+++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv1/SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:162 - over IPv6/UDP, listening at [::1]:162 -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test -| $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test -| $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp, udp6 -from pysnmp.entity.rfc3413 import ntfrcv - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) -) - -# UDP over IPv6 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 162)) -) - -# SNMPv1/2c setup - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - print( - 'Notification from ContextEngineId "{}", ContextName "{}"'.format( - contextEngineId.prettyPrint(), contextName.prettyPrint() - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py b/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py deleted file mode 100644 index 17c0e1a2e..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py +++ /dev/null @@ -1,122 +0,0 @@ -""" -Multiple SNMP USM users -+++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv3 -* with USM users: - - * 'usr-md5-des', auth: MD5, priv DES, ContextEngineId: 8000000001020304 - * 'usr-md5-none', auth: MD5, priv NONE, ContextEngineId: 8000000001020304 - * 'usr-sha-aes128', auth: SHA, priv AES, ContextEngineId: 8000000001020304 - -* over IPv4/UDP, listening at 127.0.0.1:162 -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 -| $ snmptrap -v3 -u usr-md5-none -l authNoPriv -A authkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 -| $ snmpinform -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntfrcv -from pysnmp.proto.api import v2c - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) -) - -# SNMPv3/USM setup - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) - -# user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 -# this USM entry is used for TRAP receiving purposes -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", - securityEngineId=v2c.OctetString(hexValue="8000000001020304"), -) - -# user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") - -# user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 -# this USM entry is used for TRAP receiving purposes -config.addV3User( - snmpEngine, - "usr-md5-none", - config.usmHMACMD5AuthProtocol, - "authkey1", - securityEngineId=v2c.OctetString(hexValue="8000000001020304"), -) - -# user: usr-sha-aes128, auth: SHA, priv AES -config.addV3User( - snmpEngine, - "usr-sha-aes128", - config.usmHMACSHAAuthProtocol, - "authkey1", - config.usmAesCfb128Protocol, - "privkey1", -) -# user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 -# this USM entry is used for TRAP receiving purposes -config.addV3User( - snmpEngine, - "usr-sha-aes128", - config.usmHMACSHAAuthProtocol, - "authkey1", - config.usmAesCfb128Protocol, - "privkey1", - securityEngineId=v2c.OctetString(hexValue="8000000001020304"), -) - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - print( - 'Notification from ContextEngineId "{}", ContextName "{}"'.format( - contextEngineId.prettyPrint(), contextName.prettyPrint() - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py b/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py deleted file mode 100644 index 75ae20164..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py +++ /dev/null @@ -1,99 +0,0 @@ -""" -Observe SNMP engine internal operations -+++++++++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv1/SNMPv2c -* with SNMP community "public" -* over IPv4/UDP, listening at 127.0.0.1:162 - over IPv6/UDP, listening at [::1]:162 -* registers its own execution observer to snmpEngine -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test -| $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test -| $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp, udp6 -from pysnmp.entity.rfc3413 import ntfrcv - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - - -# Execution point observer setup - -# Register a callback to be invoked at specified execution point of -# SNMP Engine and passed local variables at code point's local scope -# noinspection PyUnusedLocal,PyUnusedLocal -def requestObserver(snmpEngine, execpoint, variables, cbCtx): - print("Execution point: %s" % execpoint) - print( - "* transportDomain: %s" - % ".".join([str(x) for x in variables["transportDomain"]]) - ) - print( - "* transportAddress: %s" - % "@".join([str(x) for x in variables["transportAddress"]]) - ) - print("* securityModel: %s" % variables["securityModel"]) - print("* securityName: %s" % variables["securityName"]) - print("* securityLevel: %s" % variables["securityLevel"]) - print("* contextEngineId: %s" % variables["contextEngineId"].prettyPrint()) - print("* contextName: %s" % variables["contextName"].prettyPrint()) - print("* PDU: %s" % variables["pdu"].prettyPrint()) - - -snmpEngine.observer.registerObserver( - requestObserver, "rfc3412.receiveMessage:request", "rfc3412.returnResponsePdu" -) - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) -) - -# UDP over IPv6 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 162)) -) - -# SNMPv1/2c setup - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - print( - 'Notification from ContextEngineId "{}", ContextName "{}"'.format( - contextEngineId.prettyPrint(), contextName.prettyPrint() - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.observer.unregisterObserver() - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py b/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py deleted file mode 100644 index bb91bbfe5..000000000 --- a/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py +++ /dev/null @@ -1,94 +0,0 @@ -""" -Serve SNMP Community names defined by regexp -++++++++++++++++++++++++++++++++++++++++++++ - -Receive SNMP TRAP/INFORM messages with the following options: - -* SNMPv1/SNMPv2c -* with any SNMP community matching regexp '.*love.*' -* over IPv4/UDP, listening at 127.0.0.1:162 -* print received data on stdout - -Either of the following Net-SNMP commands will send notifications to this -receiver: - -| $ snmptrap -v1 -c rollover 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test -| $ snmpinform -v2c -c glove 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 - -The Notification Receiver below taps on v1/v2c SNMP security module -to deliver certains values, normally internal to SNMP Engine, up to -the context of user application. - -This script examines the value of CommunityName, as it came from peer SNMP -Engine, and may modify it to match the only locally configured CommunityName -'public'. This effectively makes NotificationReceiver accepting messages with -CommunityName's, not explicitly configured to local SNMP Engine. - -"""# -from pysnmp.entity import engine, config -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity.rfc3413 import ntfrcv -import re - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - - -# Register a callback to be invoked at specified execution point of -# SNMP Engine and passed local variables at execution point's local scope. -# If at this execution point passed variables are modified, their new -# values will be propagated back and used by SNMP Engine for securityName -# selection. -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def requestObserver(snmpEngine, execpoint, variables, cbCtx): - if re.match(".*love.*", str(variables["communityName"])): - print( - "Rewriting communityName '{}' from {} into 'public'".format( - variables["communityName"], - ":".join([str(x) for x in variables["transportInformation"][1]]), - ) - ) - variables["communityName"] = variables["communityName"].clone("public") - - -snmpEngine.observer.registerObserver( - requestObserver, "rfc2576.processIncomingMsg:writable" -) - -# Transport setup - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(("127.0.0.1", 162)) -) - -# SNMPv1/2c setup - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - - -# Callback function for receiving notifications -# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal -def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): - print( - 'Notification from ContextEngineId "{}", ContextName "{}"'.format( - contextEngineId.prettyPrint(), contextName.prettyPrint() - ) - ) - for name, val in varBinds: - print(f"{name.prettyPrint()} = {val.prettyPrint()}") - - -# Register SNMP Application at the SNMP engine -ntfrcv.NotificationReceiver(snmpEngine, cbFun) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send confirmations -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py b/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py deleted file mode 100644 index 1dfe1caa6..000000000 --- a/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py +++ /dev/null @@ -1,141 +0,0 @@ -""" -IPv6-to-IPv4 conversion -+++++++++++++++++++++++ - -Act as a local SNMPv1/v2c Agent listening on a UDP/IPv6 transport, relay -messages to distant SNMPv1/2c Agent over UDP/IPv4 transport: - -* with local SNMPv2c community 'public' -* local Agent listening at [::1]:161 -* remote SNMPv2c community 'public' -* remote Agent listening at 127.0.0.1:161 - -This script can be queried with the following Net-SNMP command: - -| $ snmpget -v2c -c public udp6:[::1]:161 sysDescr.0 - -due to proxy, it is equivalent to - -| $ snmpget -v2c -c public 127.0.0.1:161 sysDescr.0 - -Warning: for production operation you would need to modify this script -so that it will re-map possible duplicate request-ID values, coming in -initial request PDUs from different Managers, into unique values to -avoid sending duplicate request-IDs to Agents. - -"""# -from pysnmp.carrier.asyncore.dgram import udp, udp6 -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context -from pysnmp.proto.api import v2c -from pysnmp import error - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# -# Transport setup -# - -# Agent section - -# UDP over IPv6 -config.addTransport( - snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(("::1", 161)) -) - -# Manager section - -# UDP over IPv4 -config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openClientMode()) - -# -# SNMPv1/2c setup (Agent role) -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "1-my-area", "public") - -# -# SNMPv1/v2c setup (Manager role) -# -# Here we configure securityName lexicographically lesser than '1-my-area' -# to let it match first in snmpCommunityTable on response processing. -# - -config.addV1System(snmpEngine, "0-distant-area", "public", transportTag="remote") - -# -# Transport target used by Manager -# - -config.addTargetParams( - snmpEngine, "distant-agent-auth", "0-distant-area", "noAuthNoPriv", 1 -) -config.addTargetAddr( - snmpEngine, - "distant-agent", - udp.domainName, - ("127.0.0.1", 161), - "distant-agent-auth", - retryCount=0, - tagList="remote", -) - -# Default SNMP context -config.addContext(snmpEngine, "") - - -class CommandResponder(cmdrsp.CommandResponderBase): - cmdGenMap = { - v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), - v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), - v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), - v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(), - } - pduTypes = cmdGenMap.keys() # This app will handle these PDUs - - # SNMP request relay - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): - cbCtx = stateReference, PDU - contextEngineId = None # address authoritative SNMP Engine - try: - self.cmdGenMap[PDU.tagSet].sendPdu( - snmpEngine, - "distant-agent", - contextEngineId, - contextName, - PDU, - self.handleResponsePdu, - cbCtx, - ) - except error.PySnmpError: - self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx) - - # SNMP response relay - # noinspection PyUnusedLocal - def handleResponsePdu( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx - ): - stateReference, reqPDU = cbCtx - - if errorIndication: - PDU = v2c.apiPDU.getResponse(reqPDU) - PDU.setErrorStatus(PDU, 5) - - self.sendPdu(snmpEngine, stateReference, PDU) - - self.releaseStateInformation(stateReference) - - -CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py b/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py deleted file mode 100644 index d65098aba..000000000 --- a/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py +++ /dev/null @@ -1,145 +0,0 @@ -""" -SNMPv2c-to-SNMPv1 conversion -++++++++++++++++++++++++++++ - -Act as a local SNMPv2c Agent, relay messages to distant SNMPv1 Agent: - -* over IPv4/UDP -* with local SNMPv2c community public -* local Agent listening at 127.0.0.1:161 -* remote SNMPv1, community public -* remote Agent listening at 127.0.0.1:161 - -This script can be queried with the following Net-SNMP command: - -| $ snmpbulkwalk -v2c -c public -ObentU 127.0.0.1:161 system - -due to proxy, it is equivalent to - -| $ snmpwalk -v1 -c public 127.0.0.1:161 system - -Warning: for production operation you would need to modify this script -so that it will re-map possible duplicate request-ID values, coming in -initial request PDUs from different Managers, into unique values to -avoid sending duplicate request-IDs to Agents. - -"""# -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context -from pysnmp.proto.api import v2c -from pysnmp import error - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# -# Transport setup -# - -# Agent section - -# UDP over IPv4 -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), -) - -# Manager section - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() -) - -# -# SNMPv2c setup (Agent role) -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# -# SNMPv1 setup (Manager role) -# - -# SecurityName <-> CommunityName <-> Transport mapping -config.addV1System(snmpEngine, "distant-area", "public", transportTag="distant") - -# -# Transport target used by Manager -# - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams( - snmpEngine, "distant-agent-auth", "distant-area", "noAuthNoPriv", 0 -) - -config.addTargetAddr( - snmpEngine, - "distant-agent", - udp.domainName + (2,), - ("127.0.0.1", 161), - "distant-agent-auth", - retryCount=0, - tagList="distant", -) - -# Default SNMP context -config.addContext(snmpEngine, "") - - -class CommandResponder(cmdrsp.CommandResponderBase): - cmdGenMap = { - v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), - v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), - v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), - v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(), - } - pduTypes = cmdGenMap.keys() # This app will handle these PDUs - - # SNMP request relay - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): - cbCtx = stateReference, PDU - contextEngineId = None # address authoritative SNMP Engine - try: - self.cmdGenMap[PDU.tagSet].sendPdu( - snmpEngine, - "distant-agent", - contextEngineId, - contextName, - PDU, - self.handleResponsePdu, - cbCtx, - ) - except error.PySnmpError: - self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx) - - # SNMP response relay - # noinspection PyUnusedLocal - def handleResponsePdu( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx - ): - stateReference, reqPDU = cbCtx - - if errorIndication: - PDU = v2c.apiPDU.getResponse(reqPDU) - PDU.setErrorStatus(PDU, 5) - - self.sendPdu(snmpEngine, stateReference, PDU) - - self.releaseStateInformation(stateReference) - - -CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py b/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py deleted file mode 100644 index a7199a543..000000000 --- a/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py +++ /dev/null @@ -1,139 +0,0 @@ -""" -SNMPv2c-to-SNMPv3 conversion -++++++++++++++++++++++++++++ - -Act as a local SNMPv1/v2c Agent, relay messages to distant SNMPv3 Agent: -* over IPv4/UDP -* with local SNMPv2c community 'public' -* local Agent listening at 127.0.0.1:161 -* remote SNMPv3 user usr-md5-none, MD5 auth and no privacy protocols -* remote Agent listening at 127.0.0.1:161 - -This script can be queried with the following Net-SNMP command: - -| $ snmpget -v2c -c public 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -due to proxy, it is equivalent to - -| $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -Warning: for production operation you would need to modify this script -so that it will re-map possible duplicate request-ID values, coming in -initial request PDUs from different Managers, into unique values to -avoid sending duplicate request-IDs to Agents. - -"""# -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context -from pysnmp.proto.api import v2c -from pysnmp import error - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# -# Transport setup -# - -# Agent section - -# UDP over IPv4 -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), -) - -# Manager section - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() -) - -# -# SNMPv1/2c setup (Agent role) -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# -# SNMPv3/USM setup (Manager role) -# - -# user: usr-md5-none, auth: MD5, priv NONE -config.addV3User(snmpEngine, "usr-md5-none", config.usmHMACMD5AuthProtocol, "authkey1") - -# -# Transport target used by Manager -# - -config.addTargetParams(snmpEngine, "distant-agent-auth", "usr-md5-none", "authNoPriv") -config.addTargetAddr( - snmpEngine, - "distant-agent", - udp.domainName + (2,), - ("127.0.0.1", 161), - "distant-agent-auth", - retryCount=0, -) - -# Default SNMP context -config.addContext(snmpEngine, "") - - -class CommandResponder(cmdrsp.CommandResponderBase): - cmdGenMap = { - v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), - v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), - v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), - v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(), - } - pduTypes = cmdGenMap.keys() # This app will handle these PDUs - - # SNMP request relay - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): - cbCtx = stateReference, PDU - contextEngineId = None # address authoritative SNMP Engine - try: - self.cmdGenMap[PDU.tagSet].sendPdu( - snmpEngine, - "distant-agent", - contextEngineId, - contextName, - PDU, - self.handleResponsePdu, - cbCtx, - ) - except error.PySnmpError: - self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx) - - # SNMP response relay - # noinspection PyUnusedLocal - def handleResponsePdu( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx - ): - stateReference, reqPDU = cbCtx - - if errorIndication: - PDU = v2c.apiPDU.getResponse(reqPDU) - PDU.setErrorStatus(PDU, 5) - - self.sendPdu(snmpEngine, stateReference, PDU) - - self.releaseStateInformation(stateReference) - - -CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise diff --git a/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py b/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py deleted file mode 100644 index 5c890ad1c..000000000 --- a/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py +++ /dev/null @@ -1,148 +0,0 @@ -""" -SNMPv3-to-SNMPv2c conversion -++++++++++++++++++++++++++++ - -Act as a local SNMPv3 Agent, relay messages to distant SNMPv1/v2c Agent: -* over IPv4/UDP -* with local SNMPv3 user usr-md5-des, MD5 auth and DES privacy protocols -* local Agent listening at 127.0.0.1:161 -* remote SNMPv1, community public -* remote Agent listening at 127.0.0.1:161 - -This script can be queried with the following Net-SNMP command: - -| $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -due to proxy, it is equivalent to - -| $ snmpget -v2c -c public 127.0.0.1:161 1.3.6.1.2.1.1.1.0 - -Warning: for production operation you would need to modify this script -so that it will re-map possible duplicate request-ID values, coming in -initial request PDUs from different Managers, into unique values to -avoid sending duplicate request-IDs to Agents. - -"""# -from pysnmp.carrier.asyncore.dgram import udp -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context -from pysnmp.proto.api import v2c -from pysnmp import error - -# Create SNMP engine with autogenernated engineID and pre-bound -# to socket transport dispatcher -snmpEngine = engine.SnmpEngine() - -# -# Transport setup -# - -# Agent section - -# UDP over IPv4 -config.addTransport( - snmpEngine, - udp.domainName + (1,), - udp.UdpTransport().openServerMode(("127.0.0.1", 161)), -) - -# Manager section - -# UDP over IPv4 -config.addTransport( - snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() -) - -# -# SNMPv3/USM setup (Agent role) -# - -# user: usr-md5-des, auth: MD5, priv DES -config.addV3User( - snmpEngine, - "usr-md5-des", - config.usmHMACMD5AuthProtocol, - "authkey1", - config.usmDESPrivProtocol, - "privkey1", -) - -# -# SNMPv1/2c setup (Manager role) -# - -# SecurityName <-> CommunityName mapping -config.addV1System(snmpEngine, "my-area", "public") - -# -# Transport target used by Manager -# - -# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) -config.addTargetParams(snmpEngine, "distant-agent-auth", "my-area", "noAuthNoPriv", 0) - -config.addTargetAddr( - snmpEngine, - "distant-agent", - udp.domainName + (2,), - ("127.0.0.1", 161), - "distant-agent-auth", - retryCount=0, -) - -# Default SNMP context -config.addContext(snmpEngine, "") - - -class CommandResponder(cmdrsp.CommandResponderBase): - cmdGenMap = { - v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), - v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), - v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), - v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(), - } - pduTypes = cmdGenMap.keys() # This app will handle these PDUs - - # SNMP request relay - def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): - cbCtx = stateReference, PDU - contextEngineId = None # address authoritative SNMP Engine - try: - self.cmdGenMap[PDU.tagSet].sendPdu( - snmpEngine, - "distant-agent", - contextEngineId, - contextName, - PDU, - self.handleResponsePdu, - cbCtx, - ) - except error.PySnmpError: - self.handleResponsePdu(snmpEngine, stateReference, "error", None, cbCtx) - - # SNMP response relay - # noinspection PyUnusedLocal - def handleResponsePdu( - self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx - ): - stateReference, reqPDU = cbCtx - - if errorIndication: - PDU = v2c.apiPDU.getResponse(reqPDU) - PDU.setErrorStatus(PDU, 5) - - self.sendPdu(snmpEngine, stateReference, PDU) - - self.releaseStateInformation(stateReference) - - -CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) - -snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish - -# Run I/O dispatcher which would receive queries and send responses -try: - snmpEngine.transportDispatcher.runDispatcher() -except: - snmpEngine.transportDispatcher.closeDispatcher() - raise