1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
|
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
# License: https://www.pysnmp.com/pysnmp/license.html
#
from pyasn1.type import univ
from pysnmp import nextid
from pysnmp.proto import error, rfc1155, rfc1157
# Shortcuts to SNMP types
Integer = univ.Integer
OctetString = univ.OctetString
Null = univ.Null
null = Null("")
ObjectIdentifier = univ.ObjectIdentifier
IpAddress = rfc1155.IpAddress
NetworkAddress = rfc1155.NetworkAddress
Counter = rfc1155.Counter
Gauge = rfc1155.Gauge
TimeTicks = rfc1155.TimeTicks
Opaque = rfc1155.Opaque
VarBind = rfc1157.VarBind
VarBindList = rfc1157.VarBindList
GetRequestPDU = rfc1157.GetRequestPDU
GetNextRequestPDU = rfc1157.GetNextRequestPDU
GetResponsePDU = rfc1157.GetResponsePDU
SetRequestPDU = rfc1157.SetRequestPDU
TrapPDU = rfc1157.TrapPDU
Message = rfc1157.Message
class VarBindAPI:
"""Var-bind API."""
@staticmethod
def set_oid_value(varBind, oidVal):
"""Set OID and value components of var-bind."""
oid, val = oidVal[0], oidVal[1]
varBind.setComponentByPosition(0, oid)
if val is None:
val = null
varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(
val.getTagSet(),
val,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
innerFlag=True,
)
return varBind
@staticmethod
def get_oid_value(varBind):
"""Return OID and value components of var-bind."""
return varBind[0], varBind[1].getComponent(1)
apiVarBind = VarBindAPI() # noqa: N816
getNextRequestID = nextid.Integer(0xFFFFFF) # noqa: N816
class PDUAPI:
"""SNMP PDU API."""
_error_status = rfc1157.errorStatus.clone(0)
_error_index = Integer(0)
def set_defaults(self, pdu):
"""Set default values for SNMP PDU."""
pdu.setComponentByPosition(
0,
getNextRequestID(),
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
1,
self._error_status,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
2,
self._error_index,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3)
varBindList.clear()
@staticmethod
def get_request_id(pdu):
"""Return request ID component of SNMP PDU."""
return pdu.getComponentByPosition(0)
@staticmethod
def set_request_id(pdu, value):
"""Set request ID component of SNMP PDU."""
pdu.setComponentByPosition(0, value)
@staticmethod
def get_error_status(pdu):
"""Return error status component of SNMP PDU."""
return pdu.getComponentByPosition(1)
@staticmethod
def set_error_status(pdu, value):
"""Set error status component of SNMP PDU."""
pdu.setComponentByPosition(1, value)
@staticmethod
def get_error_index(pdu, muteErrors=False):
"""Return error index component of SNMP PDU."""
errorIndex = pdu.getComponentByPosition(2)
if errorIndex > len(pdu[3]):
if muteErrors:
return errorIndex.clone(len(pdu[3]))
raise error.ProtocolError(
f"Error index out of range: {errorIndex} > {len(pdu[3])}"
)
return errorIndex
@staticmethod
def set_error_index(pdu, value):
"""Set error index component of SNMP PDU."""
pdu.setComponentByPosition(2, value)
def set_end_of_mib_error(self, pdu, errorIndex):
"""Set end-of-MIB error status."""
self.set_error_index(pdu, errorIndex)
self.set_error_status(pdu, 2)
def set_no_such_instance_error(self, pdu, errorIndex):
"""Set no-such-instance error status."""
self.set_end_of_mib_error(pdu, errorIndex)
@staticmethod
def get_varbind_list(pdu):
"""Return var-bind list component of SNMP PDU."""
return pdu.getComponentByPosition(3)
@staticmethod
def set_varbind_list(pdu, varBindList):
"""Set var-bind list component of SNMP PDU."""
pdu.setComponentByPosition(3, varBindList)
@staticmethod
def get_varbinds(pdu):
"""Return var-binds component of SNMP PDU."""
return [
apiVarBind.get_oid_value(varBind)
for varBind in pdu.getComponentByPosition(3)
]
@staticmethod
def set_varbinds(pdu, varBinds):
"""Set var-binds component of SNMP PDU."""
varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3)
varBindList.clear()
for idx, varBind in enumerate(varBinds):
if isinstance(varBind, VarBind):
varBindList.setComponentByPosition(idx, varBind)
else:
varBindList.setComponentByPosition(idx)
apiVarBind.set_oid_value(
varBindList.getComponentByPosition(idx), varBind
)
def get_response(self, reqPDU):
"""Build response PDU."""
rspPDU = GetResponsePDU()
self.set_defaults(rspPDU)
self.set_request_id(rspPDU, self.get_request_id(reqPDU))
return rspPDU
def get_varbind_table(self, reqPDU, rspPDU):
"""Return var-bind table."""
if apiPDU.get_error_status(rspPDU) == 2:
varBindRow = [(vb[0], null) for vb in apiPDU.get_varbinds(reqPDU)]
else:
varBindRow = apiPDU.get_varbinds(rspPDU)
return [varBindRow]
def get_next_varbinds(self, varBinds, errorIndex=None):
"""Return next var-binds."""
errorIndication = None
if errorIndex:
return errorIndication, []
rspVarBinds = [(vb[0], null) for vb in varBinds]
return errorIndication, rspVarBinds
apiPDU = PDUAPI() # noqa: N816
class TrapPDUAPI:
"""SNMP trap PDU API."""
_networkAddress = None # noqa: N815
_entOid = ObjectIdentifier((1, 3, 6, 1, 4, 1, 20408)) # noqa: N815
_genericTrap = rfc1157.genericTrap.clone("coldStart") # noqa: N815
_zeroInt = univ.Integer(0) # noqa: N815
_zeroTime = TimeTicks(0) # noqa: N815
def set_defaults(self, pdu):
"""Set default values for SNMP trap PDU."""
if self._networkAddress is None:
try:
import socket
agentAddress = IpAddress(socket.gethostbyname(socket.gethostname()))
except Exception:
agentAddress = IpAddress("0.0.0.0")
self._networkAddress = NetworkAddress().setComponentByPosition(
0, agentAddress
)
pdu.setComponentByPosition(
0,
self._entOid,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
1,
self._networkAddress,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
2,
self._genericTrap,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
3,
self._zeroInt,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
pdu.setComponentByPosition(
4,
self._zeroTime,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5)
varBindList.clear()
@staticmethod
def get_enterprise(pdu):
"""Return enterprise component of SNMP trap PDU."""
return pdu.getComponentByPosition(0)
@staticmethod
def set_enterprise(pdu, value):
"""Set enterprise component of SNMP trap PDU."""
pdu.setComponentByPosition(0, value)
@staticmethod
def get_agent_address(pdu):
"""Return agent address component of SNMP trap PDU."""
return pdu.getComponentByPosition(1).getComponentByPosition(0)
@staticmethod
def set_agent_address(pdu, value):
"""Set agent address component of SNMP trap PDU."""
pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(
0, value
)
@staticmethod
def get_generic_trap(pdu):
"""Return generic trap component of SNMP trap PDU."""
return pdu.getComponentByPosition(2)
@staticmethod
def set_generic_trap(pdu, value):
"""Set generic trap component of SNMP trap PDU."""
pdu.setComponentByPosition(2, value)
@staticmethod
def get_specific_trap(pdu):
"""Return specific trap component of SNMP trap PDU."""
return pdu.getComponentByPosition(3)
@staticmethod
def set_specific_trap(pdu, value):
"""Set specific trap component of SNMP trap PDU."""
pdu.setComponentByPosition(3, value)
@staticmethod
def get_timestamp(pdu):
"""Return time stamp component of SNMP trap PDU."""
return pdu.getComponentByPosition(4)
@staticmethod
def set_timestamp(pdu, value):
"""Set time stamp component of SNMP trap PDU."""
pdu.setComponentByPosition(4, value)
@staticmethod
def get_varbind_list(pdu):
"""Return var-bind list component of SNMP trap PDU."""
return pdu.getComponentByPosition(5)
@staticmethod
def set_varbind_list(pdu, varBindList):
"""Set var-bind list component of SNMP trap PDU."""
pdu.setComponentByPosition(5, varBindList)
@staticmethod
def get_varbinds(pdu):
"""Return var-binds component of SNMP trap PDU."""
varBinds = []
for varBind in pdu.getComponentByPosition(5):
varBinds.append(apiVarBind.get_oid_value(varBind))
return varBinds
@staticmethod
def set_varbinds(pdu, varBinds):
"""Set var-binds component of SNMP trap PDU."""
varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5)
varBindList.clear()
idx = 0
for varBind in varBinds:
if isinstance(varBind, VarBind):
varBindList.setComponentByPosition(idx, varBind)
else:
varBindList.setComponentByPosition(idx)
apiVarBind.set_oid_value(
varBindList.getComponentByPosition(idx), varBind
)
idx += 1
apiTrapPDU = TrapPDUAPI() # noqa: N816
class MessageAPI:
"""SNMP message API."""
_version = rfc1157.version.clone(0)
_community = univ.OctetString("public")
def set_defaults(self, msg):
"""Set default values for SNMP message."""
msg.setComponentByPosition(
0,
self._version,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
msg.setComponentByPosition(
1,
self._community,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
)
return msg
@staticmethod
def get_version(msg):
"""Return version component of SNMP message."""
return msg.getComponentByPosition(0)
@staticmethod
def set_version(msg, value):
"""Set version component of SNMP message."""
msg.setComponentByPosition(0, value)
@staticmethod
def get_community(msg):
"""Return community component of SNMP message."""
return msg.getComponentByPosition(1)
@staticmethod
def set_community(msg, value):
"""Set community component of SNMP message."""
msg.setComponentByPosition(1, value)
@staticmethod
def get_pdu(
msg,
) -> "TrapPDU | GetRequestPDU | GetNextRequestPDU | GetResponsePDU | SetRequestPDU":
"""Return PDU component of SNMP message."""
return msg.getComponentByPosition(2).getComponent()
@staticmethod
def set_pdu(msg, value):
"""Set PDU component of SNMP message."""
msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(
value.getTagSet(),
value,
verifyConstraints=False,
matchTags=False,
matchConstraints=False,
innerFlag=True,
)
def get_response(self, reqMsg):
"""Return a response message to a request message."""
rspMsg = Message()
self.set_defaults(rspMsg)
self.set_version(rspMsg, self.get_version(reqMsg))
self.set_community(rspMsg, self.get_community(reqMsg))
self.set_pdu(rspMsg, apiPDU.get_response(self.get_pdu(reqMsg)))
return rspMsg
apiMessage = MessageAPI() # noqa: N816
|