diff options
Diffstat (limited to 'examples/v3arch/asyncore/manager')
22 files changed, 1857 insertions, 0 deletions
diff --git a/examples/v3arch/asyncore/manager/cmdgen/get-v1.py b/examples/v3arch/asyncore/manager/cmdgen/get-v1.py new file mode 100644 index 0000000..234d414 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v1.py @@ -0,0 +1,76 @@ +""" +SNMPv1 +++++++ + +* with SNMPv1, community 'public' +* over IPv4/UDP +* to an Agent at 195.218.195.228:161 +* for an OID in tuple form + +This script performs similar to the following Net-SNMP command: + +| $ snmpget -v1 -c public -ObentU 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +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('%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())) + +# 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/get-v2c-custom-timeout.py b/examples/v3arch/asyncore/manager/cmdgen/get-v2c-custom-timeout.py new file mode 100644 index 0000000..b91a4b6 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v2c-custom-timeout.py @@ -0,0 +1,79 @@ +""" +SNMPv2c, custom timeout ++++++++++++++++++++++++ + +Send a SNMP GET request: + +* with SNMPv2c, community 'public' +* over IPv4/UDP +* to an Agent at 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds', + timeout=300, # in 1/100 sec + retryCount=5 +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/get-v2c-spoof-source-address.py b/examples/v3arch/asyncore/manager/cmdgen/get-v2c-spoof-source-address.py new file mode 100644 index 0000000..998d40f --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v2c-spoof-source-address.py @@ -0,0 +1,100 @@ +""" +Spoof source address +++++++++++++++++++++ + +Send a SNMP GET request +* with SNMPv2c, community 'public' +* over IPv4/UDP +* to an Agent at 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds', + sourceAddress=('1.2.3.4', 0) +) + +# Error/response receiver +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('%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())) + +# 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/get-v3-custom-context.py b/examples/v3arch/asyncore/manager/cmdgen/get-v3-custom-context.py new file mode 100644 index 0000000..e61e538 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v3-custom-context.py @@ -0,0 +1,84 @@ +""" +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 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/get-v3-observe-request-processing.py b/examples/v3arch/asyncore/manager/cmdgen/get-v3-observe-request-processing.py new file mode 100644 index 0000000..0914ac3 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v3-observe-request-processing.py @@ -0,0 +1,105 @@ +""" +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 195.218.195.228: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 195.218.195.228: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 +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'] and variables['contextEngineId'].prettyPrint() or '<empty>',)) + print('* contextName: %s' % variables['contextName'].prettyPrint()) + print('* PDU: %s' % variables['pdu'].prettyPrint()) + +snmpEngine.observer.registerObserver( + requestObserver, + 'rfc3412.sendPdu', + 'rfc3412.receiveMessage:response' +) + +# +# 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/get-v3.py b/examples/v3arch/asyncore/manager/cmdgen/get-v3.py new file mode 100644 index 0000000..f7ff4ee --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/get-v3.py @@ -0,0 +1,82 @@ +""" +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 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/getbulk-v2c.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-v2c.py new file mode 100644 index 0000000..9f5db70 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getbulk-v2c.py @@ -0,0 +1,82 @@ +""" +Bulk walk MIB ++++++++++++++ + +Send a series of SNMP GETBULK requests +* with SNMPv2c, community 'public' +* over IPv4/UDP +* to an Agent at 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequesthandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + if errorIndication: + print(errorIndication) + return # stop on error + if errorStatus: + print('%s at %s' % ( + 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('%s = %s' % (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-v3.py b/examples/v3arch/asyncore/manager/cmdgen/getbulk-v3.py new file mode 100644 index 0000000..8bd04a5 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getbulk-v3.py @@ -0,0 +1,85 @@ +""" +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 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequesthandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + if errorIndication: + print(errorIndication) + return # stop on error + if errorStatus: + print('%s at %s' % ( + 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('%s = %s' % (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-v1.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-v1.py new file mode 100644 index 0000000..0a41a41 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-v1.py @@ -0,0 +1,83 @@ +""" +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 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +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('%s at %s' % ( + 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('%s = %s' % (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/getnext-v2c-from-specific-address.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-v2c-from-specific-address.py new file mode 100644 index 0000000..022742a --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-v2c-from-specific-address.py @@ -0,0 +1,82 @@ +""" +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 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + if errorIndication: + print(errorIndication) + return + if errorStatus: + print('%s at %s' % ( + 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('%s = %s' % (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/getnext-v2c-with-mib-compilation-and-lookup.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-v2c-with-mib-compilation-and-lookup.py new file mode 100644 index 0000000..d69abfe --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-v2c-with-mib-compilation-and-lookup.py @@ -0,0 +1,94 @@ +""" +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 195.218.195.228: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 195.218.195.228 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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +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('%s at %s' % ( + 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-v3-over-ipv6.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-v3-over-ipv6.py new file mode 100644 index 0000000..1856d80 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-v3-over-ipv6.py @@ -0,0 +1,82 @@ +""" +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 +def cbFun(snmpEngine, sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + if errorIndication: + print(errorIndication) + return + if errorStatus: + print('%s at %s' % ( + 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('%s = %s' % (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/getnext-v3-pull-subtree.py b/examples/v3arch/asyncore/manager/cmdgen/getnext-v3-pull-subtree.py new file mode 100644 index 0000000..5edc744 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/getnext-v3-pull-subtree.py @@ -0,0 +1,86 @@ +""" +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 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + if errorIndication: + print(errorIndication) + return + if errorStatus: + print('%s at %s' % ( + 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('%s = %s' % (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/set-v1.py b/examples/v3arch/asyncore/manager/cmdgen/set-v1.py new file mode 100644 index 0000000..55a8720 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/set-v1.py @@ -0,0 +1,80 @@ +""" +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 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +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('%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())) + +# 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/set-v2c.py b/examples/v3arch/asyncore/manager/cmdgen/set-v2c.py new file mode 100644 index 0000000..9f7068f --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/set-v2c.py @@ -0,0 +1,76 @@ +""" +Set scalar value +++++++++++++++++ + +Send a SNMP SET request +* with SNMPv2c with community name 'private' +* over IPv4/UDP +* to an Agent at 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/cmdgen/set-v3.py b/examples/v3arch/asyncore/manager/cmdgen/set-v3.py new file mode 100644 index 0000000..1c39d33 --- /dev/null +++ b/examples/v3arch/asyncore/manager/cmdgen/set-v3.py @@ -0,0 +1,78 @@ +""" +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 195.218.195.228: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 195.218.195.228: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, ('195.218.195.228', 161), + 'my-creds' +) + +# Error/response receiver +def cbFun(snmpEngine, sendRequestHandle, 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())) + +# 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/ntfrcv/v2c-multiple-interfaces.py b/examples/v3arch/asyncore/manager/ntfrcv/v2c-multiple-interfaces.py new file mode 100644 index 0000000..402f930 --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v2c-multiple-interfaces.py @@ -0,0 +1,70 @@ +""" +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 +def cbFun(snmpEngine, stateReference, contextEngineId, contextName, + varBinds, cbCtx): + print('Notification from ContextEngineId "%s", ContextName "%s"' % ( + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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/v2c-multiple-transports.py b/examples/v3arch/asyncore/manager/ntfrcv/v2c-multiple-transports.py new file mode 100644 index 0000000..31fcb2b --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v2c-multiple-transports.py @@ -0,0 +1,71 @@ +""" +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 +def cbFun(snmpEngine, stateReference, contextEngineId, contextName, + varBinds, cbCtx): + print('Notification from ContextEngineId "%s", ContextName "%s"' % ( + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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/v2c-observe-request-processing.py b/examples/v3arch/asyncore/manager/ntfrcv/v2c-observe-request-processing.py new file mode 100644 index 0000000..ed44146 --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v2c-observe-request-processing.py @@ -0,0 +1,94 @@ +""" +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 +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 +def cbFun(snmpEngine, stateReference, contextEngineId, contextName, + varBinds, cbCtx): + print('Notification from ContextEngineId "%s", ContextName "%s"' % ( + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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/v2c-with-regexp-community-name.py b/examples/v3arch/asyncore/manager/ntfrcv/v2c-with-regexp-community-name.py new file mode 100644 index 0000000..759bf98 --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v2c-with-regexp-community-name.py @@ -0,0 +1,88 @@ +""" +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 +from pysnmp.proto.api import v2c +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. +def requestObserver(snmpEngine, execpoint, variables, cbCtx): + if re.match('.*love.*', str(variables['communityName'])): + print('Rewriting communityName \'%s\' from %s into \'public\'' % (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 +def cbFun(snmpEngine, stateReference, contextEngineId, contextName, + varBinds, cbCtx): + print('Notification from ContextEngineId "%s", ContextName "%s"' % ( + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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/v2c-with-request-details.py b/examples/v3arch/asyncore/manager/ntfrcv/v2c-with-request-details.py new file mode 100644 index 0000000..d8619de --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v2c-with-request-details.py @@ -0,0 +1,69 @@ +""" +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 +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 %s, ContextEngineId "%s", ContextName "%s"' % ( + '@'.join([str(x) for x in execContext['transportAddress']]), + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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/v3-multiple-users.py b/examples/v3arch/asyncore/manager/ntfrcv/v3-multiple-users.py new file mode 100644 index 0000000..037062b --- /dev/null +++ b/examples/v3arch/asyncore/manager/ntfrcv/v3-multiple-users.py @@ -0,0 +1,111 @@ +""" +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 +def cbFun(snmpEngine, stateReference, contextEngineId, contextName, + varBinds, cbCtx): + print('Notification from ContextEngineId "%s", ContextName "%s"' % ( + contextEngineId.prettyPrint(), + contextName.prettyPrint() + ) + ) + for name, val in varBinds: + print('%s = %s' % (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 |