Commits

Anonymous committed 96adadc

a dozen of lightweight Twisted-based example scripts replaced more
complex example implementations used previously.

  • Participants
  • Parent commits 6027a09

Comments (0)

Files changed (31)

 Revision 4.2.5rc1
 -----------------
 
+- A dozen of lightweight Twisted-based example scripts replaced more
+  complex example implementations used previously.
 - Packet-level SNMP API (pysnmp.proto.api) getErrorIndex() method can now
   be instructed to ignore portentially malformed errorIndex SNMP packet
   value what sometimes happens with buggy SNMP implementations.

examples/v3arch/twisted/agent/cmdrsp.py

-# Command Responder over Twisted transport
-from pysnmp.entity import engine, config
-from pysnmp.entity.rfc3413 import cmdrsp, context
-from pysnmp.carrier.twisted.dgram import udp
-from pysnmp.carrier.twisted import dispatch
-#from pysnmp import debug
-
-## Optional debugging ('all' enables full debugging)
-#debug.setLogger(debug.Debug('io', 'dsp', 'msgproc', 'secmod', 'app'))
-
-# Create SNMP engine with autogenernated engineID and pre-bound
-# to socket transport dispatcher
-snmpEngine = engine.SnmpEngine()
-
-# Setup non-default transport dispatcher
-snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
-#
-# Transport setup
-#
-
-# UDP over IPv4
-config.addSocketTransport(
-    snmpEngine,
-    udp.domainName,
-    udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161))
-)
-
-#
-# SNMPv1/2c setup (if you need to handle SNMPv1/v2c messages)
-#
-
-# SecurityName <-> CommunityName mapping
-config.addV1System(snmpEngine, 'my-area', 'public')
-
-#
-# SNMPv3/USM setup (if you need to handle SNMPv3 messages)
-#
-
-# user: usr-md5-des, auth: MD5, priv DES
-config.addV3User(
-    snmpEngine, 'usr-md5-des',
-    config.usmHMACMD5AuthProtocol, 'authkey1',
-    config.usmDESPrivProtocol, 'privkey1'
-)
-
-# user: usr-none-none, auth: NONE, priv NONE
-config.addV3User(
-    snmpEngine, 'usr-none-none'
-)
-
-# user: usr-md5-none, auth: MD5, priv NONE
-config.addV3User(
-    snmpEngine, 'usr-md5-none',
-    config.usmHMACMD5AuthProtocol, 'authkey1'
-)
-
-# user: usr-sha-aes128, auth: SHA, priv AES
-config.addV3User(
-    snmpEngine, 'usr-sha-aes128',
-    config.usmHMACSHAAuthProtocol, 'authkey1',
-    config.usmAesCfb128Protocol, 'privkey1'
-)
-
-# user: usr-md5-aes256, auth: MD5, priv AES256
-config.addV3User(
-    snmpEngine, 'usr-md5-aes256',
-    config.usmHMACMD5AuthProtocol, 'authkey1',
-    config.usmAesCfb256Protocol, 'privkey1'
-)
-
-# user: usr-md5-aes192, auth: MD5, priv AES192
-config.addV3User(
-    snmpEngine, 'usr-md5-aes192',
-    config.usmHMACMD5AuthProtocol, 'authkey1',
-    config.usmAesCfb192Protocol, 'privkey1'
-)
-
-# user: usr-md5-3des, auth: MD5, priv 3DES
-config.addV3User(
-    snmpEngine, 'usr-md5-3des',
-    config.usmHMACMD5AuthProtocol, 'authkey1',
-    config.usm3DESEDEPrivProtocol, 'privkey1'
-)
-
-#
-# Access control (VACM) setup
-#
-
-# Configure VACM from the scratch
-
-# default context
-config.addContext(snmpEngine, '')
-
-# allow full MIB access for each user
-config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) 
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1,3,6), (1,3,6)) 
-
-#
-# CommandResponder could serve multiple independent MIB trees
-# selected by ContextName parameter. The default ContextName is
-# an empty string, this is where SNMP engine's LCD also lives.
-#
-snmpContext = context.SnmpContext(snmpEngine)
-
-# Register SNMP Applications at the SNMP engine
-cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
-cmdrsp.SetCommandResponder(snmpEngine, snmpContext)
-cmdrsp.NextCommandResponder(snmpEngine, snmpContext)
-cmdrsp.BulkCommandResponder(snmpEngine, snmpContext)
-
-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 

examples/v3arch/twisted/agent/cmdrsp/v1-read-and-write-communities.py

+#
+# Command Responder
+#
+# Listen and 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
+# 
+# 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 twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413 import cmdrsp, context
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.carrier.twisted import dispatch
+
+# Create SNMP engine with autogenernated engineID and pre-bound
+# to socket transport dispatcher
+snmpEngine = engine.SnmpEngine()
+
+# Transport setup
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# UDP over IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/cmdrsp/v2c-custom-scalar-mib-objects.py

+#
+# Command Responder
+#
+# 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
+# 
+# Either of the following Net-SNMP's commands will walk this Agent:
+#
+# $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6
+#
+import sys
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413 import cmdrsp, context
+from pysnmp.proto import rfc1902
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.carrier.twisted import dispatch
+
+# Create SNMP engine with autogenernated engineID and pre-bound
+# to socket transport dispatcher
+snmpEngine = engine.SnmpEngine()
+
+# Transport setup
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# UDP over IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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):
+    def getValue(self, name, idx):
+        return self.getSyntax().clone(
+            'Python %s running on a %s platform' % (sys.version, sys.platform)
+        )
+
+mibBuilder.exportSymbols(
+    '__MY_MIB', MibScalar((1,3,6,5,1), rfc1902.OctetString()),
+                MyStaticMibScalarInstance((1,3,6,5,1), (0,), rfc1902.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)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/cmdrsp/v2c-multiple-interfaces.py

+#
+# Command Responder
+#
+# 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's 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 twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413 import cmdrsp, context
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.carrier.twisted import dispatch
+
+# Create SNMP engine with autogenernated engineID and pre-bound
+# to socket transport dispatcher
+snmpEngine = engine.SnmpEngine()
+
+# Transport setup
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# UDP over IPv4 at 127.0.0.1:161
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName + (1,),
+    udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161))
+)
+
+# UDP over IPv4 at 127.0.0.2:161
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName + (2,),
+    udp.UdpTwistedTransport().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)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/cmdrsp/v3-multiple-users.py

+#
+# Command Responder
+#
+# 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's 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 twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413 import cmdrsp, context
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.carrier.twisted import dispatch
+
+# Create SNMP engine with autogenernated engineID and pre-bound
+# to socket transport dispatcher
+snmpEngine = engine.SnmpEngine()
+
+# Transport setup
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# UDP over IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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'
+)
+# 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)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/ntforg.py

-# Notification originator
-from twisted.internet import reactor
-from pysnmp.entity import engine, config
-from pysnmp.carrier.twisted import dispatch
-from pysnmp.carrier.twisted.dgram import udp
-from pysnmp.entity.rfc3413 import context
-from pysnmp.entity.rfc3413.twisted import ntforg
-from pysnmp.proto.api import v2c
-#from pysnmp import debug
-
-## Optional debugging ('all' enables full debugging)
-#debug.setLogger(debug.Debug('io', 'dsp', 'msgproc', 'secmod', 'app'))
-
-# Send either Teap or Inform request
-doInform = True
-
-# Create SNMP engine instance
-snmpEngine = engine.SnmpEngine()
-
-# Set Twisted dispatcher
-snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
-
-# 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-1', 'my-area', 'noAuthNoPriv', 0)
-config.addTargetParams(snmpEngine, 'my-creds-1', 'my-area', 'noAuthNoPriv', 1)
-
-#
-# SNMPv3/USM setup (choose any one if you use SNMPv3/USM)
-#
-
-# 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-3', 'usr-md5-des', 'authPriv')
-
-## user: usr-none-none, auth: NONE, priv NONE
-#config.addV3User(
-#    snmpEngine, 'usr-none-none'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv')
-
-## 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')
-
-## user: usr-sha-aes128, auth: SHA, priv AES
-#config.addV3User(
-#    snmpEngine, 'usr-sha-aes128',
-#    config.usmHMACSHAAuthProtocol, 'authkey1',
-#    config.usmAesCfb128Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes128', 'authPriv')
-
-## user: usr-md5-aes256, auth: MD5, priv AES256
-#config.addV3User(
-#    snmpEngine, 'usr-md5-aes256',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usmAesCfb256Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-aes256', 'authPriv')
-
-## user: usr-md5-aes192, auth: MD5, priv AES192
-#config.addV3User(
-#    snmpEngine, 'usr-md5-aes192',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usmAesCfb192Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-aes192', 'authPriv')
-
-## user: usr-md5-3des, auth: MD5, priv 3DES
-#config.addV3User(
-#    snmpEngine, 'usr-md5-3des',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usm3DESEDEPrivProtocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-3des', 'authPriv')
-
-#
-# Setup transport endpoint and bind it with security settings yielding
-# a target name. Since Notifications could be sent to multiple Managers
-# at once, more than one target entry may be configured (and tagged).
-#
-
-# UDP/IPv4
-config.addSocketTransport(
-    snmpEngine,
-    udp.domainName,
-    udp.UdpTwistedTransport().openClientMode()
-)
-config.addTargetAddr(
-    snmpEngine, 'my-nms-1',
-    udp.domainName, ('127.0.0.1', 162),
-    'my-creds-1',
-    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', doInform and 'inform' or 'trap'
-)
-
-#
-# Notifications carry potentially confidential information from
-# the Agent. Therefore access control is to be setup allowing
-# NotificationOriginator access to certain portions of Agent MIB.
-#
-config.addContext(snmpEngine, '')
-# SNMPv1
-config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1,3,6))
-# SNMPv2c
-config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1,3,6))
-# SNMPv3
-config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authPriv', (), (), (1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'authPriv', (), (), (1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-md5-aes192', 'authPriv', (), (),(1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-md5-aes256', 'authPriv', (), (),(1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (), (),(1,3,6)) 
-config.addVacmUser(snmpEngine, 3, 'usr-md5-3des', 'authPriv', (), (),(1,3,6)) 
-
-# SNMP context
-snmpContext = context.SnmpContext(snmpEngine)
-
-#
-# Twisted API follows
-#
-
-# Error/confirmation reciever
-def receiveResponse(cbCtx):
-    (sendRequestHandle, errorIndication) = cbCtx
-    print('Notification %s, status - %s' % (sendRequestHandle, errorIndication and errorIndication or 'delivered'))
-    reactor.stop()
-    
-df = ntforg.NotificationOriginator(snmpContext).sendNotification(
-     snmpEngine,
-     # Notification targets
-     'my-notification',
-     # Trap OID (SNMPv2-MIB::coldStart)
-     (1,3,6,1,6,3,1,1,5,1),
-     # ((oid, value), ... )
-     ( ((1,3,6,1,2,1,1,1), v2c.OctetString('Example Notificator')),
-       ((1,3,6,1,2,1,1,5), v2c.OctetString('Notificator Example')) ),
-)
-
-if doInform:
-    df.addCallback(receiveResponse)
-    reactor.run()

examples/v3arch/twisted/agent/ntforg/inform-v2c.py

+#
+# Notification Originator
+#
+# Send SNMP INFORM notification using the following options:
+#
+# * SNMPv2c
+# * with community name 'public'
+# * over IPv4/UDP
+# * using Twisted framework for network transport
+# * 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'
+#
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.entity.rfc3413 import context
+from pysnmp.entity.rfc3413.twisted import ntforg
+from pysnmp.proto import rfc1902
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Set Twisted dispatcher
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# SNMPv2c setup
+
+# 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)
+
+# Transport setup
+
+#
+# Setup transport endpoint and bind it with security settings yielding
+# a target name. Since Notifications could be sent to multiple Managers
+# at once, more than one target entry may be configured (and tagged).
+#
+
+# UDP/IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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))
+
+# Create default SNMP context where contextEngineId == SnmpEngineId
+snmpContext = context.SnmpContext(snmpEngine)
+
+# Create Notification Originator App instance. 
+ntfOrg = ntforg.NotificationOriginator(snmpContext)
+ 
+# Error/confirmation receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
+    print('Notification status - %s' % (
+        errorIndication and errorIndication or 'delivered'
+      )
+    )
+    # Optionally stop Twisted reactor
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = ntfOrg.sendNotification(
+    snmpEngine,
+    # Notification targets
+    'my-notification',
+    # Trap OID (SNMPv2-MIB::coldStart)
+    (1,3,6,1,6,3,1,1,5,1),
+    # ( (oid, value), ... )
+    ( ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Example Notificator')),
+      ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('Notificator Example')) )
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+print('Notification is scheduled to be sent')
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/ntforg/inform-v3.py

+#
+# Notification Originator
+#
+# Send SNMP INFORM notification using the following options:
+#
+# * SNMPv3
+# * with user 'usr-md5-none', auth: MD5, priv NONE
+# * over IPv4/UDP
+# * using Twisted framework for network transport
+# * to a Manager at 127.0.0.1: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'
+#
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.entity.rfc3413 import context
+from pysnmp.entity.rfc3413.twisted import ntforg
+from pysnmp.proto import rfc1902
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Set Twisted dispatcher
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# SNMPv3/USM setup
+
+# Add USM user
+config.addV3User(
+    snmpEngine, 'usr-md5-none',
+    config.usmHMACMD5AuthProtocol, 'authkey1'
+)
+config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv')
+
+# Transport setup
+
+#
+# Setup transport endpoint and bind it with security settings yielding
+# a target name. Since Notifications could be sent to multiple Managers
+# at once, more than one target entry may be configured (and tagged).
+#
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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))
+
+# Create default SNMP context where contextEngineId == SnmpEngineId
+snmpContext = context.SnmpContext(snmpEngine)
+
+# Create Notification Originator App instance. 
+ntfOrg = ntforg.NotificationOriginator(snmpContext)
+ 
+# Error/confirmation receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
+    print('Notification status - %s' % (
+        errorIndication and errorIndication or 'delivered'
+      )
+    )
+    # Optionally stop Twisted reactor
+    reactor.stop()
+
+# Build and submit notification message to dispatcher
+df = ntfOrg.sendNotification(
+    snmpEngine,
+    # Notification targets
+    'my-notification',
+    # Trap OID (SNMPv2-MIB::coldStart)
+    (1,3,6,1,6,3,1,1,5,1),
+    # ( (oid, value), ... )
+    ( ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('system name')), )
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+print('Notification is scheduled to be sent')
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/ntforg/trap-v1.py

+#
+# Notification Originator
+#
+# Send SNMP notification using the following options:
+#
+# * SNMPv1
+# * with community name 'public'
+# * over IPv4/UDP
+# * using Twisted framework for network transport
+# * 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'
+#
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.entity.rfc3413 import context
+from pysnmp.entity.rfc3413.twisted import ntforg
+from pysnmp.proto import rfc1902
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Set Twisted dispatcher
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# SNMPv1 setup
+
+# SecurityName <-> CommunityName mapping
+config.addV1System(snmpEngine, 'my-area', 'public')
+
+# Specify security settings per SecurityName (SNMPv1 -> 0)
+config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
+
+# Transport setup
+#
+# Setup transport endpoint and bind it with security settings yielding
+# a target name. Since Notifications could be sent to multiple Managers
+# at once, more than one target entry may be configured (and tagged).
+#
+
+# UDP/IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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 (1), securityLevel
+# and SecurityName
+config.addContext(snmpEngine, '')
+config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1,3,6))
+
+# Create default SNMP context where contextEngineId == SnmpEngineId
+snmpContext = context.SnmpContext(snmpEngine)
+
+# Create Notification Originator App instance. 
+ntfOrg = ntforg.NotificationOriginator(snmpContext)
+ 
+# Prepare notification to be sent yielding Twisted deferred object
+ntforg.NotificationOriginator(snmpContext).sendNotification(
+    snmpEngine,
+    # Notification targets
+    'my-notification',
+    # TRAP OID: Generic Trap #6 (enterpriseSpecific) and Specific Trap 432
+    '1.3.6.1.4.1.20408.4.1.1.2.0.432',
+    # additional var-binds holding SNMPv1 TRAP details
+    (
+        # Uptime value with 12345
+        (rfc1902.ObjectName('1.3.6.1.2.1.1.3.0'),
+         rfc1902.TimeTicks(12345)),
+        # Agent Address with '127.0.0.1'
+        (rfc1902.ObjectName('1.3.6.1.6.3.18.1.3.0'),
+         rfc1902.IpAddress('127.0.0.1')),
+        # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2
+        (rfc1902.ObjectName('1.3.6.1.6.3.1.1.4.3.0'),
+         rfc1902.ObjectName('1.3.6.1.4.1.20408.4.1.1.2')),
+        # managed object '1.3.6.1.2.1.1.1.0' = 'my system'
+        (rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'),
+         rfc1902.OctetString('my system'))
+    )
+)
+
+print('Notification is scheduled to be sent')
+
+# Schedule Twisted mainloop shutdown shortly
+reactor.callWhenRunning(lambda: reactor.stop())
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/ntforg/trap-v2c-multiple-targets.py

+#
+# Notification Originator
+#
+# Send SNMP TRAP notifications to multiple Managers using the
+# following options:
+#
+# * SNMPv2c
+# * with community name 'public'
+# * over IPv4/UDP
+# * using Twisted framework for network transport
+# * send TRAP notification
+# * to multiple Managers at 127.0.0.1:162, 127.0.0.2: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'
+#
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.entity.rfc3413 import context
+from pysnmp.entity.rfc3413.twisted import ntforg
+from pysnmp.proto import rfc1902
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Set Twisted dispatcher
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# SNMPv2c setup
+
+# 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)
+
+# Transport setup
+
+#
+# Setup transport endpoint and bind it with security settings yielding
+# a target name. Since Notifications could be sent to multiple Managers
+# at once, more than one target entry may be configured (and tagged).
+#
+
+# UDP/IPv4
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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.2', 162),
+    'my-creds',
+    tagList='all-my-managers'
+)
+# Third target
+config.addTargetAddr(
+    snmpEngine, 'my-nms-3',
+    udp.domainName, ('127.0.0.3', 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))
+
+# Create default SNMP context where contextEngineId == SnmpEngineId
+snmpContext = context.SnmpContext(snmpEngine)
+
+# Create Notification Originator App instance. 
+ntfOrg = ntforg.NotificationOriginator(snmpContext)
+ 
+# Build and submit notification message to dispatcher
+ntfOrg.sendNotification(
+    snmpEngine,
+    # Notification targets
+    'my-notification',
+    # Trap OID (SNMPv2-MIB::coldStart)
+    (1,3,6,1,6,3,1,1,5,1),
+    # ( (oid, value), ... )
+    ( ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Example Notificator')),
+      ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('Notificator Example')) )
+)
+
+print('Notification is scheduled to be sent')
+
+# Schedule Twisted mainloop shutdown shortly
+reactor.callWhenRunning(lambda: reactor.stop())
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/agent/ntforg/trap-v3.py

+#
+# Notification Originator
+#
+# Send SNMP TRAP notification using the following options:
+#
+# * SNMPv3
+# * with user 'usr-md5-des', auth: MD5, priv DES
+# * over IPv4/UDP
+# * using Twisted framework for network transport
+# * 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'
+#
+from twisted.internet import reactor
+from pysnmp.entity import engine, config
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+from pysnmp.entity.rfc3413 import context
+from pysnmp.entity.rfc3413.twisted import ntforg
+from pysnmp.proto import rfc1902
+
+# 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=rfc1902.OctetString(hexValue='8000000001020304')
+)
+
+# Set Twisted dispatcher
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+# SNMPv3/USM setup
+
+# Add USM user
+config.addV3User(
+    snmpEngine, 'usr-md5-des',
+    config.usmHMACMD5AuthProtocol, 'authkey1',
+    config.usmDESPrivProtocol, 'privkey1'
+)
+config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')
+
+# Transport setup
+
+# Setup transport endpoint and bind it with security settings yielding
+# a target name
+config.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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))
+
+# Create default SNMP context where contextEngineId == SnmpEngineId
+snmpContext = context.SnmpContext(snmpEngine)
+
+# Create Notification Originator App instance. 
+ntfOrg = ntforg.NotificationOriginator(snmpContext)
+ 
+# Build and submit notification message to dispatcher
+ntfOrg.sendNotification(
+    snmpEngine,
+    # Notification targets
+    'my-notification',
+    # Trap OID (SNMPv2-MIB::coldStart)
+    (1,3,6,1,6,3,1,1,5,1),
+    # ( (oid, value), ... )
+    ( ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('system name')), )
+)
+
+print('Notification is scheduled to be sent')
+
+# Schedule Twisted mainloop shutdown shortly
+reactor.callWhenRunning(lambda: reactor.stop())
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/bulkgen.py

-# BULK Command Generator
-from twisted.internet import reactor, defer
-from pysnmp.entity import engine, config
-from pysnmp.carrier.twisted import dispatch
-from pysnmp.carrier.twisted.dgram import udp
-from pysnmp.entity.rfc3413.twisted import cmdgen
-from pyasn1.type import univ
-#from pysnmp import debug
-
-## Optional debugging ('all' enables full debugging)
-#debug.setLogger(debug.Debug('io', 'dsp', 'msgproc', 'secmod', 'app'))
-
-# 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')
-
-# Set Twisted dispatcher
-snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
-
-# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
-#config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0)
-config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
-
-#
-# SNMPv3/USM setup (choose any one if you use SNMPv3/USM)
-#
-
-## 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')
-
-## user: usr-none-none, auth: NONE, priv NONE
-#config.addV3User(
-#    snmpEngine, 'usr-none-none'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv')
-
-## 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')
-
-## user: usr-sha-aes128, auth: SHA, priv AES
-#config.addV3User(
-#    snmpEngine, 'usr-sha-aes128',
-#    config.usmHMACSHAAuthProtocol, 'authkey1',
-#    config.usmAesCfb128Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes128', 'authPriv')
-
-## user: usr-md5-aes256, auth: MD5, priv AES256
-#config.addV3User(
-#    snmpEngine, 'usr-md5-aes256',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usmAesCfb256Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-aes256', 'authPriv')
-
-## user: usr-md5-aes192, auth: MD5, priv AES192
-#config.addV3User(
-#    snmpEngine, 'usr-md5-aes192',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usmAesCfb192Protocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-aes192', 'authPriv')
-
-## user: usr-md5-3des, auth: MD5, priv 3DES
-#config.addV3User(
-#    snmpEngine, 'usr-md5-3des',
-#    config.usmHMACMD5AuthProtocol, 'authkey1',
-#    config.usm3DESEDEPrivProtocol, 'privkey1'
-#)
-#config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-3des', 'authPriv')
-
-#
-# Setup transport endpoint and bind it with security settings yielding
-# a target name (choose one entry depending of the transport needed).
-#
-
-# UDP/IPv4
-config.addSocketTransport(
-    snmpEngine,
-    udp.domainName,
-    udp.UdpTwistedTransport().openClientMode()
-)
-config.addTargetAddr(
-    snmpEngine, 'my-router',
-    udp.domainName, ('127.0.0.1', 161),
-    'my-creds'
-)
-
-
-# Twisted API follows
-
-# Error/response reciever
-def receiveResponse(cbCtx):
-    (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx
-    if errorIndication:
-        print('Error: %s' % errorIndication)
-        reactor.stop()
-        return
-    if errorStatus and errorStatus != 2:
-        print('%s at %s' % (
-            errorStatus.prettyPrint(),
-            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
-            )
-        )
-        reactor.stop()
-        return
-    for varBindRow in varBindTable:
-        for oid, val in varBindRow:
-            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
-
-    for o, v in varBindTable[-1]:
-        if not isinstance(v, univ.Null):
-            break
-    else:
-        reactor.stop()  # no more objects available
-        return
-
-    df = defer.Deferred()
-    df.addCallback(receiveResponse)
-    return df  # this is to indicate that we wish to continue walking
-
-# Prepare initial request to be sent
-df = cmdgen.BulkCommandGenerator().sendReq(
-    snmpEngine,
-    'my-router',
-    0, 25,   # non-repeaters, max-repetitions
-    ( ((1,3,6,1,2,1,1), None),
-      ((1,3,6,1,4,1,1), None) )
-    )
-
-df.addCallback(receiveResponse)
-
-reactor.run()

examples/v3arch/twisted/manager/cmdgen/get-v1.py

+#
+# GET Command Generator
+#
+# Send a SNMP GET request
+#     with SNMPv1, community 'public'
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().openClientMode()
+)
+config.addTargetAddr(
+    snmpEngine, 'my-router',
+    udp.domainName, ('127.0.0.1', 161),
+    'my-creds'
+)
+
+# Error/response receiver
+def cbFun(cbCtx):
+    (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('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for oid, val in varBinds:
+            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.GetCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    ( ('1.3.6.1.2.1.1.1.0', None), ('1.3.6.1.2.1.1.2.0', None) ),
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/get-v2c-custom-timeout.py

+#
+# GET Command Generator
+#
+# Send a SNMP GET request
+#     with SNMPv2c, community 'public'
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().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
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
+    if errorIndication:
+        print(errorIndication)
+    elif errorStatus:
+        print('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for oid, val in varBinds:
+            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.GetCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    ( ('1.3.6.1.2.1.1.1.0', None), ),
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/get-v3-custom-context.py

+#
+# GET Command Generator
+#
+# Send a SNMP GET request
+#     with SNMPv3 with user 'usr-md5-none', SHA auth and no privacy protocols
+#     for MIB instance identified by contextEngineId: 8000000001020304,
+#                                    contextName: my-context
+#     using Twisted framework for network transport
+#     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 8000000001020304 -n my-context -ObentU 127.0.0.1:161  1.3.6.1.2.1.1.1.0
+#
+from twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.proto import rfc1902
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().openClientMode()
+)
+config.addTargetAddr(
+    snmpEngine, 'my-router',
+    udp.domainName, ('127.0.0.1', 161),
+    'my-creds'
+)
+
+# Error/response receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
+    if errorIndication:
+        print(errorIndication)
+    elif errorStatus:
+        print('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for oid, val in varBinds:
+            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.GetCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    ( ('1.3.6.1.2.1.1.1.0', None), ),
+    contextEngineId=rfc1902.OctetString(hexValue='8000000001020304'),
+    contextName=rfc1902.OctetString('my-context')
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/get-v3.py

+#
+# GET Command Generator
+#
+# Send a SNMP GET request
+#     with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().openClientMode()
+)
+config.addTargetAddr(
+    snmpEngine, 'my-router',
+    udp.domainName, ('127.0.0.1', 161),
+    'my-creds'
+)
+
+# Error/response receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
+    if errorIndication:
+        print(errorIndication)
+    elif errorStatus:
+        print('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for oid, val in varBinds:
+            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.GetCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    ( ('1.3.6.1.2.1.1.1.0', None), ),
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/getbulk-v2c.py

+#
+# GETBULK Command Generator
+#
+# Send a series of SNMP GETBULK requests
+#     with SNMPv2c, community 'public'
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.proto import rfc1905
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().openClientMode()
+)
+config.addTargetAddr(
+    snmpEngine, 'my-router',
+    udp.domainName, ('127.0.0.1', 161),
+    'my-creds'
+)
+
+# Error/response receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx
+    if errorIndication:
+        print(errorIndication)
+    elif errorStatus:
+        print('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for varBindRow in varBindTable:
+            for oid, val in varBindRow:
+                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+        # Stop reactor when we are done walking (optional)
+        for oid, val in varBindRow:
+            if not val.isSameTypeWith(rfc1905.endOfMibView):
+                break
+        else:
+            reactor.stop()
+            return
+
+        # Re-create deferred for next GETBULK iteration
+        df = defer.Deferred()
+        df.addCallback(cbFun)
+
+        return df  # This also indicates that we wish to continue walking
+
+    # Stop reactor on SNMP error (optional)
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.BulkCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    0, 25,   # non-repeaters, max-repetitions
+    ( ('1.3.6.1.2.1.1', None), ('1.3.6.1.4.1.1', None) )
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/getbulk-v3.py

+#
+# GETBULK Command Generator
+#
+# Send a series of SNMP GETBULK requests
+#     with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols
+#     over IPv4/UDP
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.proto import rfc1905
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+
+#
+# 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.addSocketTransport(
+    snmpEngine,
+    udp.domainName,
+    udp.UdpTwistedTransport().openClientMode()
+)
+config.addTargetAddr(
+    snmpEngine, 'my-router',
+    udp.domainName, ('127.0.0.1', 161),
+    'my-creds'
+)
+
+# Error/response receiver
+def cbFun(cbCtx):
+    (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx
+    if errorIndication:
+        print(errorIndication)
+    elif errorStatus:
+        print('%s at %s' % (
+                errorStatus.prettyPrint(),
+                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
+            )
+        )
+    else:
+        for varBindRow in varBindTable:
+            for oid, val in varBindRow:
+                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
+
+        # Stop reactor when we are done walking (optional)
+        for oid, val in varBindRow:
+            if not val.isSameTypeWith(rfc1905.endOfMibView):
+                break
+        else:
+            reactor.stop()
+            return
+
+        # Re-create deferred for next GETBULK iteration
+        df = defer.Deferred()
+        df.addCallback(cbFun)
+        return df  # This also indicates that we wish to continue walking
+
+    # Stop reactor on SNMP error (optional)
+    reactor.stop()
+
+# Prepare request to be sent yielding Twisted deferred object
+df = cmdgen.BulkCommandGenerator().sendReq(
+    snmpEngine,
+    'my-router',
+    0, 25,   # non-repeaters, max-repetitions
+    ( ((1,3,6,1,2,1,1), None), ((1,3,6,1,4,1,1), None) )
+)
+
+# Register error/response receiver function at deferred
+df.addCallback(cbFun)
+
+# Run Twisted main loop
+reactor.run()

examples/v3arch/twisted/manager/cmdgen/getnext-v1.py

+#
+# GETNEXT Command Generator
+#
+# Send a series of SNMP GETNEXT requests
+#     with SNMPv1, community 'public'
+#     using Twisted framework for network transport
+#     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 twisted.internet import reactor, defer
+from pysnmp.entity import engine, config
+from pysnmp.entity.rfc3413.twisted import cmdgen
+from pysnmp.proto import rfc1905
+from pysnmp.carrier.twisted import dispatch
+from pysnmp.carrier.twisted.dgram import udp
+
+# Create SNMP engine instance
+snmpEngine = engine.SnmpEngine()
+
+# Instantiate and register Twisted dispatcher at SNMP engine
+snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher())
+