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 429 430 431 432 433 434 435 436 437 438 439 440
|
import unittest
import os
import threading
import multiprocessing
import platform
from datetime import timedelta
from snimpy import basictypes, snmp, mib
import agent
class TestSnmpRetriesTimeout(unittest.TestCase):
"""Live modification of retry and timeout values for a session"""
def setUp(self):
self.session = snmp.Session(host="localhost",
community="public",
version=2)
def testGetRetries(self):
"""Get default retries value"""
self.assertEqual(self.session.retries, 5)
def testGetTimeout(self):
"""Get default timeout value"""
self.assertEqual(self.session.timeout, 1000000)
def testSetRetries(self):
"""Try to set a new retry value"""
self.session.retries = 2
self.assertEqual(self.session.retries, 2)
self.session.retries = 0
self.assertEqual(self.session.retries, 0)
def testSetTimeout(self):
"""Try to set a new timeout value"""
self.session.timeout = 500000
self.assertEqual(self.session.timeout, 500000)
def testErrors(self):
"""Try invalid values for timeout and retries"""
self.assertRaises(ValueError, setattr, self.session, "timeout", 0)
self.assertRaises(ValueError, setattr, self.session, "timeout", -30)
self.assertRaises(ValueError, setattr, self.session, "retries", -5)
class TestSnmpSession(unittest.TestCase):
"""Test for session creation using SNMPv1/v2c/v3"""
def testSnmpV1(self):
"""Check initialization of SNMPv1 session"""
snmp.Session(host="localhost",
community="public",
version=1)
def testSnmpV2(self):
"""Check initialization of SNMPv2 session"""
snmp.Session(host="localhost",
community="public",
version=2)
def testSnmpV3(self):
"""Check initialization of SNMPv3 session"""
snmp.Session(host="localhost",
version=3,
secname="readonly",
authprotocol="MD5", authpassword="authpass",
privprotocol="AES", privpassword="privpass")
def testSnmpV3Protocols(self):
"""Check accepted auth and privacy protocols"""
for auth in ["MD5", "SHA"]:
for priv in ["AES", "AES128", "DES"]:
snmp.Session(host="localhost",
version=3,
secname="readonly",
authprotocol=auth, authpassword="authpass",
privprotocol=priv, privpassword="privpass")
self.assertRaises(ValueError,
snmp.Session,
host="localhost",
version=3,
secname="readonly",
authprotocol="NOEXIST", authpassword="authpass",
privprotocol="AES", privpassword="privpass")
self.assertRaises(ValueError,
snmp.Session,
host="localhost",
version=3,
secname="readonly",
authprotocol="MD5", authpassword="authpass",
privprotocol="NOEXIST", privpassword="privpass")
def testRepresentation(self):
"""Test session representation"""
s = snmp.Session(host="localhost",
community="public",
version=1)
self.assertEqual(repr(s), "Session(host=localhost,version=1)")
def testSnmpV3SecLevels(self):
"""Check accepted security levels"""
auth = "MD5"
priv = "DES"
snmp.Session(host="localhost",
version=3,
secname="readonly",
authprotocol=auth, authpassword="authpass",
privprotocol=priv, privpassword="privpass")
snmp.Session(host="localhost",
version=3,
secname="readonly",
authprotocol=None,
privprotocol=None)
snmp.Session(host="localhost",
version=3,
secname="readonly",
authprotocol=auth, authpassword="authpass",
privprotocol=None)
class TestSnmp1(unittest.TestCase):
"""
Test communication with an agent with SNMPv1.
"""
version = 1
@classmethod
def addAgent(cls, community, auth, priv):
a = agent.TestAgent(community=community,
authpass=auth,
privpass=priv)
cls.agents.append(a)
return a
@classmethod
def setUpClass(cls):
mib.load('IF-MIB')
mib.load('SNMPv2-MIB')
cls.agents = []
cls.agent = cls.addAgent('public',
'public-authpass', 'public-privpass')
def setUp(self):
params = self.setUpSession(self.agent, 'public')
self.session = snmp.Session(**params)
def setUpSession(self, agent, password):
return dict(host="127.0.0.1:{}".format(agent.port),
community=password,
version=self.version)
@classmethod
def tearDownClass(cls):
for a in cls.agents:
a.terminate()
def testGetString(self):
"""Get a string value"""
ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
oid, a = self.session.get(ooid)[0]
self.assertEqual(oid, ooid)
self.assertEqual(a, b"Snimpy Test Agent public")
def testGetInteger(self):
"""Get an integer value"""
oid, a = self.session.get(mib.get('IF-MIB', 'ifNumber').oid + (0,))[0]
self.assertTrue(a > 1) # At least lo and another interface
def testGetEnum(self):
"""Get an enum value"""
oid, a = self.session.get(mib.get('IF-MIB', 'ifType').oid + (1,))[0]
self.assertEqual(a, 24) # This is software loopback
b = basictypes.build('IF-MIB', 'ifType', a)
self.assertEqual(b, "softwareLoopback")
def testGetMacAddress(self):
"""Get a MAC address"""
mib.load(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"SNIMPY-MIB.mib"))
oid, a = self.session.get((1, 3, 6, 1, 2, 1, 45121, 1, 15, 0))[0]
self.assertEqual(a, b"\x11\x12\x13\x14\x15\x16")
b = basictypes.build('SNIMPY-MIB', 'snimpyMacAddress', a)
self.assertEqual(b, "11:12:13:14:15:16")
def testGetObjectId(self):
"""Get ObjectId."""
ooid = mib.get('SNMPv2-MIB', 'sysObjectID').oid + (0,)
oid, a = self.session.get(ooid)[0]
self.assertEqual(oid, ooid)
self.assertEqual(a, (1, 3, 6, 1, 4, 1, 9, 1, 1208))
def testInexistant(self):
"""Get an inexistant value"""
try:
self.session.get((1, 2, 3))
self.assertFalse("we should have got an exception")
except snmp.SNMPException as ex:
self.assertTrue(isinstance(ex, snmp.SNMPNoSuchName) or
isinstance(ex, snmp.SNMPNoSuchObject))
def testSetIpAddress(self):
"""Set IpAddress."""
self.setAndCheck('snimpyIpAddress', '10.14.12.12')
def testSetString(self):
"""Set String."""
self.setAndCheck('snimpyString', 'hello')
def testSetInteger(self):
"""Set Integer."""
self.setAndCheck('snimpyInteger', 1574512)
def testSetEnum(self):
"""Set Enum."""
self.setAndCheck('snimpyEnum', 'testing')
def testSetObjectId(self):
"""Set ObjectId."""
self.setAndCheck('snimpyObjectId', (1, 2, 3, 4, 5, 6))
def testSetCounter(self):
"""Set Counter."""
self.setAndCheck('snimpyCounter', 545424)
def testSetGauge(self):
"""Set Gauge."""
self.setAndCheck('snimpyGauge', 4857544)
def testSetBoolean(self):
"""Set Boolean."""
self.setAndCheck('snimpyBoolean', True)
def testSetTimeticks(self):
"""Set Timeticks."""
self.setAndCheck('snimpyTimeticks', timedelta(3, 18))
def testSetBits(self):
"""Set Bits."""
self.setAndCheck('snimpyBits', ["third", "last"])
def testSetMacAddress(self):
"""Set a MAC address."""
self.setAndCheck('snimpyMacAddress', "a0:b0:c0:d0:e:ff")
oid, a = self.session.get((1, 3, 6, 1, 2, 1, 45121, 1, 15, 0))[0]
# This is software loopback
self.assertEqual(a, b"\xa0\xb0\xc0\xd0\x0e\xff")
def setAndCheck(self, oid, value):
"""Set and check a value"""
mib.load(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"SNIMPY-MIB.mib"))
ooid = mib.get('SNIMPY-MIB', oid).oid + (0,)
self.session.set(ooid,
basictypes.build('SNIMPY-MIB', oid, value))
self.assertEqual(
basictypes.build('SNIMPY-MIB', oid, self.session.get(ooid)[0][1]),
basictypes.build('SNIMPY-MIB', oid, value))
def testMultipleGet(self):
"""Get multiple values at once"""
ooid1 = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
ooid2 = mib.get('IF-MIB', 'ifNumber').oid + (0,)
ooid3 = mib.get('IF-MIB', 'ifType').oid + (1,)
(oid1, a1), (oid2, a2), (oid3, a3) = self.session.get(
ooid1, ooid2, ooid3)
self.assertEqual(oid1, ooid1)
self.assertEqual(oid2, ooid2)
self.assertEqual(oid3, ooid3)
self.assertEqual(a1, b"Snimpy Test Agent public")
self.assertTrue(a2 > 1)
b = basictypes.build('IF-MIB', 'ifType', a3)
self.assertEqual(b, "softwareLoopback")
def testBulk(self):
"""Try to set bulk to different values"""
self.session.bulk = 32
self.assertEqual(self.session.bulk, 32)
self.assertRaises(ValueError,
setattr,
self.session,
"bulk",
0)
self.assertRaises(ValueError,
setattr,
self.session,
"bulk",
-10)
def testWalk(self):
"""Check if we can walk"""
ooid = mib.get("IF-MIB", "ifDescr").oid
results = self.session.walk(ooid)
self.assertEqual(tuple(results),
((ooid + (1,), b"lo"),
(ooid + (2,), b"eth0"),
(ooid + (3,), b"eth1")))
def testSeveralSessions(self):
"""Test with two sessions"""
agent2 = self.addAgent('private',
'private-authpass', 'private-privpass')
params = self.setUpSession(agent2, 'private')
session2 = snmp.Session(**params)
ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
oid1, a1 = self.session.get(ooid)[0]
oid2, a2 = session2.get(ooid)[0]
self.assertEqual(oid1, ooid)
self.assertEqual(oid2, ooid)
self.assertEqual(a1, b"Snimpy Test Agent public")
self.assertEqual(a2, b"Snimpy Test Agent private")
@unittest.skipIf(platform.python_implementation() == "PyPy",
"unreliable test with Pypy")
def testMultipleThreads(self):
"""Test with multiple sessions in different threads."""
count = 20
agents = []
for i in range(count):
agents.append(self.addAgent('community{}'.format(i),
'community{}-authpass'.format(i),
'community{}-privpass'.format(i)))
ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
threads = []
successes = []
failures = []
lock = multiprocessing.Lock()
# Start one thread
def run(i):
params = self.setUpSession(agents[i], 'community{}'.format(i))
session = snmp.Session(**params)
session.timeout = 10 * 1000 * 1000
oid, a = session.get(ooid)[0]
exp = ("Snimpy Test Agent community{}".format(i)).encode('ascii')
with lock:
if oid == ooid and \
a == exp:
successes.append("community{}".format(i))
else:
failures.append("community{}".format(i))
for i in range(count):
threads.append(threading.Thread(target=run, args=(i,)))
for i in range(count):
threads[i].start()
for i in range(count):
threads[i].join()
self.assertEqual(failures, [])
self.assertEqual(sorted(successes),
sorted(["community{}".format(i)
for i in range(count)]))
class TestSnmp2(TestSnmp1):
"""Test communication with an agent with SNMPv2."""
version = 2
def testInexistantNone(self):
"""Get an inexistant value but request none"""
params = self.setUpSession(self.agent, 'public')
params['none'] = True
session = snmp.Session(**params)
oid, a = session.get((1, 2, 3))[0]
self.assertEqual(a, None)
def testSetCounter64(self):
"""Set Counter64."""
self.setAndCheck('snimpyCounter64', 2 ** 47 + 1)
def testWalk(self):
"""Check if we can walk"""
ooid = mib.get("IF-MIB", "ifDescr").oid
self.session.bulk = 4
results = self.session.walk(ooid)
self.assertEqual(tuple(results),
((ooid + (1,), b"lo"),
(ooid + (2,), b"eth0"),
(ooid + (3,), b"eth1")))
self.session.bulk = 2
results = self.session.walk(ooid)
self.assertEqual(tuple(results),
((ooid + (1,), b"lo"),
(ooid + (2,), b"eth0"),
(ooid + (3,), b"eth1")))
class TestSnmp3(TestSnmp2):
"""Test communicaton with an agent with SNMPv3."""
version = 3
def setUpSession(self, agent, password):
return dict(host="127.0.0.1:{}".format(agent.port),
version=3,
secname="read-write",
authprotocol="MD5",
authpassword="{}-authpass".format(password),
privprotocol="AES",
privpassword="{}-privpass".format(password))
class TestSnmpTransports(unittest.TestCase):
"""Test communication using IPv6."""
ipv6 = True
@classmethod
def setUpClass(cls):
mib.load('IF-MIB')
mib.load('SNMPv2-MIB')
def _test(self, ipv6, host):
m = agent.TestAgent(ipv6)
session = snmp.Session(
host="{}:{}".format(host, m.port),
community="public",
version=2)
try:
ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
oid, a = session.get(ooid)[0]
self.assertEqual(a, b"Snimpy Test Agent public")
finally:
m.terminate()
def testIpv4(self):
"""Test IPv4 transport"""
self._test(False, "127.0.0.1")
def testIpv4WithDNS(self):
"""Test IPv4 transport with name resolution"""
self._test(False, "localhost")
def testIpv6(self):
"""Test IPv6 transport"""
self._test(True, "[::1]")
|