1"""
2SNMPv2c-to-SNMPv1 conversion
3++++++++++++++++++++++++++++
4
5Act as a local SNMPv2c Agent, relay messages to distant SNMPv1 Agent:
6
7* over IPv4/UDP
8* with local SNMPv2c community public
9* local Agent listening at 127.0.0.1:161
10* remote SNMPv1, community public
11* remote Agent listening at 104.236.166.95:161
12
13This script can be queried with the following Net-SNMP command:
14
15| $ snmpbulkwalk -v2c -c public -ObentU 127.0.0.1:161 system
16
17due to proxy, it is equivalent to
18
19| $ snmpwalk -v1 -c public 104.236.166.95:161 system
20
21Warning: for production operation you would need to modify this script
22so that it will re-map possible duplicate request-ID values, coming in
23initial request PDUs from different Managers, into unique values to
24avoid sending duplicate request-IDs to Agents.
25
26"""#
27from pysnmp.carrier.asyncore.dgram import udp
28from pysnmp.entity import engine, config
29from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context
30from pysnmp.proto.api import v2c
31from pysnmp import error
32
33# Create SNMP engine with autogenernated engineID and pre-bound
34# to socket transport dispatcher
35snmpEngine = engine.SnmpEngine()
36
37#
38# Transport setup
39#
40
41# Agent section
42
43# UDP over IPv4
44config.addTransport(
45    snmpEngine,
46    udp.domainName + (1,),
47    udp.UdpTransport().openServerMode(('127.0.0.1', 161))
48)
49
50# Manager section
51
52# UDP over IPv4
53config.addTransport(
54    snmpEngine,
55    udp.domainName + (2,),
56    udp.UdpTransport().openClientMode()
57)
58
59#
60# SNMPv2c setup (Agent role)
61#
62
63# SecurityName <-> CommunityName mapping
64config.addV1System(snmpEngine, 'my-area', 'public')
65
66#
67# SNMPv1 setup (Manager role)
68#
69
70# SecurityName <-> CommunityName <-> Transport mapping
71config.addV1System(snmpEngine, 'distant-area', 'public', transportTag='distant')
72
73#
74# Transport target used by Manager
75#
76
77# Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
78config.addTargetParams(snmpEngine, 'distant-agent-auth', 'distant-area',
79                       'noAuthNoPriv', 0)
80
81config.addTargetAddr(
82    snmpEngine, 'distant-agent',
83    udp.domainName + (2,), ('104.236.166.95', 161),
84    'distant-agent-auth', retryCount=0, tagList='distant'
85)
86
87# Default SNMP context
88config.addContext(snmpEngine, '')
89
90
91class CommandResponder(cmdrsp.CommandResponderBase):
92    cmdGenMap = {
93        v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
94        v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
95        v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
96        v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
97    }
98    pduTypes = cmdGenMap.keys()  # This app will handle these PDUs
99
100    # SNMP request relay
101    def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
102                            PDU, acInfo):
103        cbCtx = stateReference, PDU
104        contextEngineId = None  # address authoritative SNMP Engine
105        try:
106            self.cmdGenMap[PDU.tagSet].sendPdu(
107                snmpEngine, 'distant-agent',
108                contextEngineId, contextName,
109                PDU,
110                self.handleResponsePdu, cbCtx
111            )
112        except error.PySnmpError:
113            self.handleResponsePdu(
114                snmpEngine, stateReference, 'error', None, cbCtx
115            )
116
117    # SNMP response relay
118    # noinspection PyUnusedLocal
119    def handleResponsePdu(self, snmpEngine, sendRequestHandle,
120                          errorIndication, PDU, cbCtx):
121        stateReference, reqPDU = cbCtx
122
123        if errorIndication:
124            PDU = v2c.apiPDU.getResponse(reqPDU)
125            PDU.setErrorStatus(PDU, 5)
126
127        self.sendPdu(
128            snmpEngine, stateReference, PDU
129        )
130
131        self.releaseStateInformation(stateReference)
132
133
134CommandResponder(snmpEngine, context.SnmpContext(snmpEngine))
135
136snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish
137
138# Run I/O dispatcher which would receive queries and send responses
139try:
140    snmpEngine.transportDispatcher.runDispatcher()
141except:
142    snmpEngine.transportDispatcher.closeDispatcher()
143    raise
144