1"""
2Multiple SNMP communities
3+++++++++++++++++++++++++
4
5Respond to SNMP GET/SET/GETNEXT queries with the following options:
6
7* SNMPv1
8* with SNMP community "public" (read access) or "private" (write access)
9* allow access to SNMPv2-MIB objects (1.3.6.1.2.1)
10* over IPv4/UDP, listening at 127.0.0.1:161
11
12Allow read/write access to all objects in the same MIB subtree.
13
14The following Net-SNMP's commands will GET/SET a value at this Agent:
15
16| $ snmpget -v1 -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0
17| $ snmpset -v1 -c private 127.0.0.1 SNMPv2-MIB::sysLocation.0 s "far away"
18
19"""#
20from pysnmp.entity import engine, config
21from pysnmp.entity.rfc3413 import cmdrsp, context
22from pysnmp.carrier.asyncore.dgram import udp
23
24# Create SNMP engine with autogenernated engineID and pre-bound
25# to socket transport dispatcher
26snmpEngine = engine.SnmpEngine()
27
28# Transport setup
29
30# UDP over IPv4
31config.addTransport(
32    snmpEngine,
33    udp.domainName,
34    udp.UdpTransport().openServerMode(('127.0.0.1', 161))
35)
36
37# SNMPv1 setup
38
39# SecurityName <-> CommunityName mapping.
40# Here we configure two distinct CommunityName's to control read and write
41# operations.
42config.addV1System(snmpEngine, 'my-read-area', 'public')
43config.addV1System(snmpEngine, 'my-write-area', 'private')
44
45# Allow full MIB access for this user / securityModels at VACM
46config.addVacmUser(snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1))
47config.addVacmUser(snmpEngine, 1, 'my-write-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
48
49# Get default SNMP context this SNMP engine serves
50snmpContext = context.SnmpContext(snmpEngine)
51
52# Register SNMP Applications at the SNMP engine for particular SNMP context
53cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
54cmdrsp.SetCommandResponder(snmpEngine, snmpContext)
55cmdrsp.NextCommandResponder(snmpEngine, snmpContext)
56
57# Register an imaginary never-ending job to keep I/O dispatcher running forever
58snmpEngine.transportDispatcher.jobStarted(1)
59
60# Run I/O dispatcher which would receive queries and send responses
61try:
62    snmpEngine.transportDispatcher.runDispatcher()
63except:
64    snmpEngine.transportDispatcher.closeDispatcher()
65    raise
66