Пример #1
0
 def testIndexes(self):
     """Test that we can retrieve correctly the index of tables"""
     self.assertEqual([str(i) for i in mib.get("SNIMPY-MIB", "snimpySimpleTable").index], ["snimpySimpleIndex"])
     self.assertEqual(
         [str(i) for i in mib.get("SNIMPY-MIB", "snimpyComplexTable").index],
         ["snimpyComplexFirstIP", "snimpyComplexSecondIP"],
     )
Пример #2
0
 def testOid(self):
     """Test OID basic type"""
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assert_(isinstance(a, basictypes.Oid))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger").oid)
     # Suboid
     self.assert_((list(mib.get("SNIMPY-MIB",
                                "snimpyInteger").oid) + [2, 3]) in a)
     self.assert_((list(mib.get("SNIMPY-MIB",
                                "snimpyInteger").oid)[:-1] +
                   [29, 3]) not in a)
     # Ability to extract a component
     self.assertEqual(a[0], 1)
     self.assertEqual(a[1], 3)
     self.assertEqual(a[-3], 45121)
     self.assertEqual(a[-1], 3)
     self.assertEqual(a[:3], (1, 3, 6))
     # Also accepts list
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          (1, 2, 3, 4))
     self.assertEqual(a, (1, 2, 3, 4))
     self.assert_((1, 2, 3, 4, 5) in a)
     self.assert_((3, 4, 5, 6) not in a)
Пример #3
0
 def testOidGreedy(self):
     """Test greediness of fromOid."""
     tt = {
         "snimpyIndexVarLen":
         ((5, 104, 101, 108, 108, 111, 111, 111, 111), (6, "hello")),
         "snimpyIndexFixedLen":
         ((104, 101, 108, 108, 111, 49, 49, 111), (6, "hello1")),
         "snimpyIndexImplied":
         ((104, 101, 108, 108, 111, 50), (6, "hello2")),
         "snimpyComplexFirstIP":
         ((15, 15, 16, 100, 23, 74, 87), (4, "15.15.16.100")),
         "snimpySimpleIndex": ((17, 19, 20), (1, 17)),
         "snimpyIndexOidVarLen": ((3, 247, 145, 475568, 475, 263),
                                  (4, (247, 145, 475568))),
     }
     for t in tt:
         self.assertEqual(mib.get("SNIMPY-MIB", t).type.fromOid(
             mib.get("SNIMPY-MIB", t), tt[t][0]),
             tt[t][1])
     # Test if too short
     tt = {"snimpyComplexFirstIP": (17, 19, 20),
           "snimpyIndexFixedLen": (104, 101, 108),
           "snimpyIndexVarLen": (6, 102, 103, 104, 105),
           "snimpyIndexOidVarLen": (3, 247, 145),
           }
     for t in tt:
         self.assertRaises(ValueError,
                           mib.get("SNIMPY-MIB", t).type.fromOid,
                           mib.get("SNIMPY-MIB", t), tt[t])
Пример #4
0
 def testEnums(self):
     """Test that we got the enum values correctly"""
     self.assertEqual(mib.get('SNIMPY-MIB', "snimpyInteger").enum, None)
     self.assertEqual(mib.get("SNIMPY-MIB", "snimpyEnum").enum,
                      {1: "up",
                       2: "down",
                       3: "testing"})
     self.assertEqual(mib.get("SNIMPY-MIB", "snimpyBits").enum,
                      {0: "first",
                       1: "second",
                       2: "third",
                       7: "last"})
Пример #5
0
    def testTooLargeOid(self):
        """Handle the special case of octet string as OID with too large octets.

        See: https://github.com/vincentbernat/snimpy/pull/14
        """
        self.assertEqual(mib.get("SNIMPY-MIB",
                                 "snimpyIndexImplied").type.fromOid(
                                     mib.get("SNIMPY-MIB",
                                             "snimpyIndexImplied"),
                                     (104, 0xff00 | 101, 108, 108, 111)),
                         (5, basictypes.build("SNIMPY-MIB",
                                              "snimpyIndexImplied",
                                              "hello")))
Пример #6
0
 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.assert_(a2 > 1)
     b = basictypes.build("IF-MIB", "ifType", a3)
     self.assertEqual(b, "softwareLoopback")
Пример #7
0
 def testImplied(self):
     """Check that we can get implied attribute for a given table"""
     self.assertEqual(
         mib.get("SNIMPY-MIB",
                 'snimpySimpleTable').implied,
         False)
     self.assertEqual(
         mib.get("SNIMPY-MIB",
                 'snimpyComplexTable').implied,
         False)
     self.assertEqual(
         mib.get("SNIMPY-MIB",
                 'snimpyIndexTable').implied,
         True)
Пример #8
0
 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, " ".join(os.uname()))
     self.assert_(a2 > 1)
     b = basictypes.build('IF-MIB', 'ifType', a3)
     self.assertEqual(b, "softwareLoopback")
Пример #9
0
    def testTypeName(self):
        """Check that we can get the current declared type name"""
        table = mib.get("SNIMPY-MIB", "snimpyInetAddressTable")
        attr = table.index[1]

        self.assertEqual(attr.typeName, b"InetAddress")

        attr.typeName = b"InetAddressIPv4"
        self.assertEqual(attr.typeName, b"InetAddressIPv4")

        attr.typeName = b"InetAddressIPv6"
        self.assertEqual(attr.typeName, b"InetAddressIPv6")

        attr = mib.get("SNIMPY-MIB", "snimpySimpleIndex")
        self.assertEqual(attr.typeName, b"Integer32")
Пример #10
0
 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(results,
                      ((ooid + (1,), b"lo"),
                       (ooid + (2,), b"eth0"),
                       (ooid + (3,), b"eth1"),
                       (mib.get("IF-MIB", "ifType").oid + (1,), 24)))
     self.session.bulk = 2
     results = self.session.walk(ooid)
     self.assertEqual(results[:2],
                      ((ooid + (1,), b"lo"),
                       (ooid + (2,), b"eth0")))
Пример #11
0
    def testTypes(self):
        """Test that we get the correct types"""
        tt = {
            "snimpyIpAddress": basictypes.IpAddress,
            "snimpyString": basictypes.OctetString,
            "snimpyOctetString": basictypes.OctetString,
            "snimpyUnicodeString": basictypes.OctetString,
            "snimpyMacAddress": basictypes.OctetString,
            "snimpyInteger": basictypes.Integer,
            "snimpyEnum": basictypes.Enum,
            "snimpyObjectId": basictypes.Oid,
            "snimpyBoolean": basictypes.Boolean,
            "snimpyCounter": basictypes.Unsigned32,
            "snimpyGauge": basictypes.Unsigned32,
            "snimpyTimeticks": basictypes.Timeticks,
            "snimpyCounter64": basictypes.Unsigned64,
            "snimpyBits": basictypes.Bits,
            "snimpySimpleIndex": basictypes.Integer,
            "snimpyComplexFirstIP": basictypes.IpAddress,
            "snimpyComplexSecondIP": basictypes.IpAddress,
            "snimpyComplexState": basictypes.Enum
        }
        for t in tt:
            self.assertEqual(mib.get('SNIMPY-MIB', t).type, tt[t])

        # Also check we get an exception when no type available
        def call():
            mib.get('SNIMPY-MIB', 'snimpySimpleTable').type

        self.assertRaises(mib.SMIException, call)
Пример #12
0
 def testEnums(self):
     """Test that we got the enum values correctly"""
     self.assertEqual(mib.get('SNIMPY-MIB', "snimpyInteger").enum, None)
     self.assertEqual(
         mib.get("SNIMPY-MIB", "snimpyEnum").enum, {
             1: "up",
             2: "down",
             3: "testing"
         })
     self.assertEqual(
         mib.get("SNIMPY-MIB", "snimpyBits").enum, {
             0: "first",
             1: "second",
             2: "third",
             7: "last"
         })
Пример #13
0
    def testTypes(self):
        """Test that we get the correct types"""
        tt = {"snimpyIpAddress": basictypes.IpAddress,
              "snimpyString": basictypes.OctetString,
              "snimpyOctetString": basictypes.OctetString,
              "snimpyUnicodeString": basictypes.OctetString,
              "snimpyMacAddress": basictypes.OctetString,
              "snimpyInteger": basictypes.Integer,
              "snimpyEnum": basictypes.Enum,
              "snimpyObjectId": basictypes.Oid,
              "snimpyBoolean": basictypes.Boolean,
              "snimpyCounter": basictypes.Unsigned32,
              "snimpyGauge": basictypes.Unsigned32,
              "snimpyTimeticks": basictypes.Timeticks,
              "snimpyCounter64": basictypes.Unsigned64,
              "snimpyBits": basictypes.Bits,
              "snimpySimpleIndex": basictypes.Integer,
              "snimpyComplexFirstIP": basictypes.IpAddress,
              "snimpyComplexSecondIP": basictypes.IpAddress,
              "snimpyComplexState": basictypes.Enum}
        for t in tt:
            self.assertEqual(mib.get('SNIMPY-MIB', t).type, tt[t])

        # Also check we get an exception when no type available
        def call():
            mib.get('SNIMPY-MIB', 'snimpySimpleTable').type
        self.assertRaises(mib.SMIException, call)
Пример #14
0
 def testWalk(self):
     """Check if we can walk"""
     ooid = mib.get("IF-MIB", "ifDescr").oid
     results = self.session.walk(ooid)
     self.assertEqual(results,
                      ((ooid + (1,), b"lo"),
                       (ooid + (2,), b"eth0"),
                       (ooid + (3,), b"eth1")))
Пример #15
0
 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")))
Пример #16
0
 def testOid(self):
     """Test OID basic type"""
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assert_(isinstance(a, basictypes.Oid))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger").oid)
     # Suboid
     self.assert_((list(mib.get("SNIMPY-MIB", "snimpyInteger").oid) +
                   [2, 3]) in a)
     self.assert_((list(mib.get("SNIMPY-MIB", "snimpyInteger").oid)[:-1] +
                   [29, 3]) not in a)
     # Also accepts list
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId", (1, 2, 3, 4))
     self.assertEqual(a, (1, 2, 3, 4))
     self.assert_((1, 2, 3, 4, 5) in a)
     self.assert_((3, 4, 5, 6) not in a)
Пример #17
0
 def _locate(self, attribute):
     for m in self._loaded:
         try:
             a = mib.get(m, attribute)
             return (m, a)
         except mib.SMIException:
             pass
     raise AttributeError("{0} is not an attribute".format(attribute))
Пример #18
0
 def testSeveralSessions(self):
     ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid + (0,)
     oid1, a1 = self.session.get(ooid)[0]
     oid2, a2 = self.session2.get(ooid)[0]
     self.assertEqual(oid1, ooid)
     self.assertEqual(oid2, ooid)
     self.assertEqual(a1, b"Snimpy Test Agent")
     self.assertEqual(a2, b"Snimpy Test Agent")
Пример #19
0
 def _locate(self, attribute):
     for m in self._loaded:
         try:
             a = mib.get(m, attribute)
             return (m, a)
         except mib.SMIException:
             pass
     raise AttributeError("{0} is not an attribute".format(attribute))
Пример #20
0
 def testOid(self):
     """Test OID basic type"""
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assert_(isinstance(a, basictypes.Oid))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger").oid)
     # Suboid
     self.assert_((list(mib.get("SNIMPY-MIB",
                                "snimpyInteger").oid) + [2,3]) in a)
     self.assert_((list(mib.get("SNIMPY-MIB",
                                "snimpyInteger").oid)[:-1] + [29,3]) not in a)
     # Also accepts list
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          (1,2,3,4))
     self.assertEqual(a, (1,2,3,4))
     self.assert_((1,2,3,4,5) in a)
     self.assert_((3,4,5,6) not in a)
Пример #21
0
 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),
     )
Пример #22
0
 def testGet(self):
     """Test that we can get all named attributes"""
     for i in self.scalars:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Scalar))
     for i in self.tables:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Table))
     for i in self.columns:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Column))
     for i in self.nodes:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Node))
     for i in self.notifications:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i),
                                 mib.Notification))
Пример #23
0
 def _test(self, ipv6, host):
     m = agent.TestAgent(ipv6)
     session = snmp.Session(host="{0}:{1}".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()
Пример #24
0
 def testGetByOid(self):
     """Test that we can get all named attributes by OID."""
     for i in self.scalars:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Scalar))
     for i in self.tables:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Table))
     for i in self.columns:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Column))
     for i in self.nodes:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Node))
Пример #25
0
 def testGetByOid(self):
     """Test that we can get all named attributes by OID."""
     for i in self.scalars:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Scalar))
     for i in self.tables:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Table))
     for i in self.columns:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Column))
     for i in self.nodes:
         nodebyname = mib.get('SNIMPY-MIB', i)
         self.assertEqual(str(mib.getByOid(nodebyname.oid)), i)
         self.assert_(isinstance(mib.getByOid(nodebyname.oid), mib.Node))
Пример #26
0
 def testTableColumnRelation(self):
     """Test that we can get the column from the table and vice-versa"""
     for i in self.tables:
         table = mib.get("SNIMPY-MIB", i)
         for r in table.columns:
             self.assert_(isinstance(r, mib.Column))
             self.assertEqual(str(r.table), str(i))
             self.assert_(str(r).startswith(str(i).replace("Table", "")))
         columns = sorted([str(rr) for rr in self.columns if str(rr).startswith(str(i).replace("Table", ""))])
         tcolumns = [str(rr) for rr in table.columns]
         tcolumns.sort()
         self.assertEqual(columns, tcolumns)
     for r in self.columns:
         column = mib.get("SNIMPY-MIB", r)
         table = column.table
         self.assert_(isinstance(table, mib.Table))
         prefix = str(table).replace("Table", "")
         self.assertEqual(prefix, str(r)[: len(prefix)])
Пример #27
0
 def testGet(self):
     """Test that we can get all named attributes"""
     for i in self.scalars:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Scalar))
     for i in self.tables:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Table))
     for i in self.columns:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Column))
     for i in self.nodes:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i), mib.Node))
     for i in self.notifications:
         self.assertEqual(str(mib.get('SNIMPY-MIB', i)), i)
         self.assert_(isinstance(mib.get('SNIMPY-MIB', i),
                      mib.Notification))
Пример #28
0
 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))
Пример #29
0
def build(mibname, node, value):
    """Build a new basic type with the given value.

    :param mibname: The MIB to use to locate the entity.
    :param node: The node that will be attached to this type.
    :param value: The initial value to set for the type.
    :return: A :class:`Type` instance
    """
    m = mib.get(mibname, node)
    t = m.type(m, value)
    return t
Пример #30
0
 def _test(self, ipv6, host):
     m = agent.TestAgent(ipv6)
     session = snmp.Session(host="{0}:{1}".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()
Пример #31
0
 def testOid(self):
     """Test conversion to/from OID."""
     tt = { ("snimpySimpleIndex", 47): (47,),
            ("snimpyComplexFirstIP", "10.14.15.4"): (10, 14, 15, 4),
            ("snimpyComplexSecondIP", (14,15,16,17)): (14, 15, 16, 17),
            ("snimpyIndexOidVarLen", (47, 48, 49)): (3, 47, 48, 49),
            ("snimpyIndexVarLen", "hello1"): tuple([len("hello1")] + [ord(a) for a in "hello1"]),
            ("snimpyIndexFixedLen", "hello2"): tuple(ord(a) for a in "hello2"),
            ("snimpyIndexImplied", "hello3"): tuple(ord(a) for a in "hello3"),
            }
     for t,v in tt:
         oid = basictypes.build("SNIMPY-MIB",
                                t,
                                v).toOid()
         self.assertEqual(oid,
                          tt[t,v])
         # Test double conversion
         self.assertEqual(mib.get("SNIMPY-MIB", t).type.fromOid(
                 mib.get("SNIMPY-MIB", t), oid),
                          (len(tt[t,v]), v))
Пример #32
0
def build(mibname, node, value):
    """Build a new basic type with the given value.

    :param mibname: The MIB to use to locate the entity.
    :param node: The node that will be attached to this type.
    :param value: The initial value to set for the type.
    :return: A :class:`Type` instance
    """
    m = mib.get(mibname, node)
    t = m.type(m, value)
    return t
Пример #33
0
 def testOidConversion(self):
     """Test conversion to/from OID."""
     tt = {
         ("snimpySimpleIndex", 47): (47, ),
         ("snimpyComplexFirstIP", "10.14.15.4"): (10, 14, 15, 4),
         ("snimpyComplexSecondIP", (14, 15, 16, 17)): (14, 15, 16, 17),
         ("snimpyIndexOidVarLen", (47, 48, 49)): (3, 47, 48, 49),
         ("snimpyIndexVarLen", "hello1"):
         tuple([len("hello1")] + [ord(a) for a in "hello1"]),
         ("snimpyIndexFixedLen", "hello2"):
         tuple(ord(a) for a in "hello2"),
         ("snimpyIndexImplied", "hello3"):
         tuple(ord(a) for a in "hello3"),
     }
     for t, v in tt:
         oid = basictypes.build("SNIMPY-MIB", t, v).toOid()
         self.assertEqual(oid, tt[t, v])
         # Test double conversion
         self.assertEqual(
             mib.get("SNIMPY-MIB", t).type.fromOid(mib.get("SNIMPY-MIB", t),
                                                   oid), (len(tt[t, v]), v))
Пример #34
0
    def testTypeOverrides(self):
        """Check that we can override a type"""
        table = mib.get("SNIMPY-MIB", "snimpyInetAddressTable")
        addrtype_attr = table.index[0]
        addr_attr = table.index[1]

        # Try overriding to IPv4 with a byte string name.
        addrtype = addrtype_attr.type(addrtype_attr, "ipv4")
        self.assertEqual(addrtype, "ipv4")
        addr_attr.typeName = b"InetAddressIPv4"
        ipv4 = u"127.0.0.1"
        ipv4_oid = (4, 127, 0, 0, 1)

        addr = addr_attr.type(addr_attr, ipv4)
        self.assertEqual(str(addr), ipv4)
        self.assertEqual(addr.toOid(), ipv4_oid)

        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv4_oid)
        self.assertEqual(addr_len, ipv4_oid[0] + 1)
        self.assertEqual(str(addr), ipv4)
        self.assertEqual(addr.toOid(), ipv4_oid)

        # Try both IPv6 and non-bytes name.
        addrtype = addrtype_attr.type(addrtype_attr, "ipv6")
        self.assertEqual(addrtype, "ipv6")
        addr_attr.typeName = u"InetAddressIPv6"
        # Snimpy does not use leading zeroes.
        ipv6 = u'102:304:506:708:90a:b0c:d0e:f01'
        ipv6_oid = (16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                    0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x01)

        addr = addr_attr.type(addr_attr, ipv6)
        self.assertEqual(str(addr), ipv6)
        self.assertEqual(addr.toOid(), ipv6_oid)

        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv6_oid)
        self.assertEqual(addr_len, ipv6_oid[0] + 1)
        self.assertEqual(str(addr), ipv6)
        self.assertEqual(addr.toOid(), ipv6_oid)

        # Try a type from a different module (chosen because snmpwalk
        # prints IPv6 addresses incorrectly).
        ipv6_1xformat = u'1:2:3:4:5:6:7:8:9:a:b:c:d:e:f:1'
        addr_attr.typeName = "PhysAddress"

        addr = addr_attr.type(addr_attr, ipv6_1xformat)
        self.assertEqual(str(addr), ipv6_1xformat)
        self.assertEqual(addr.toOid(), ipv6_oid)

        # Try overriding back to the default.
        del addr_attr.typeName
        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv4_oid)
        self.assertEqual(bytes(addr), b"\x7f\0\0\1")
Пример #35
0
 def testTableColumnRelation(self):
     """Test that we can get the column from the table and vice-versa"""
     for i in self.tables:
         table = mib.get('SNIMPY-MIB', i)
         for r in table.columns:
             self.assert_(isinstance(r, mib.Column))
             self.assertEqual(str(r.table), str(i))
             self.assert_(str(r).startswith(str(i).replace("Table", "")))
         columns = sorted([
             str(rr) for rr in self.columns
             if str(rr).startswith(str(i).replace("Table", ""))
         ])
         tcolumns = [str(rr) for rr in table.columns]
         tcolumns.sort()
         self.assertEqual(columns, tcolumns)
     for r in self.columns:
         column = mib.get('SNIMPY-MIB', r)
         table = column.table
         self.assert_(isinstance(table, mib.Table))
         prefix = str(table).replace("Table", "")
         self.assertEqual(prefix, str(r)[:len(prefix)])
Пример #36
0
    def testTypeOverrides(self):
        """Check that we can override a type"""
        table = mib.get("SNIMPY-MIB", "snimpyInetAddressTable")
        addrtype_attr = table.index[0]
        addr_attr = table.index[1]

        # Try overriding to IPv4 with a byte string name.
        addrtype = addrtype_attr.type(addrtype_attr, "ipv4")
        self.assertEqual(addrtype, "ipv4")
        addr_attr.typeName = b"InetAddressIPv4"
        ipv4 = u"127.0.0.1"
        ipv4_oid = (4, 127, 0, 0, 1)

        addr = addr_attr.type(addr_attr, ipv4)
        self.assertEqual(str(addr), ipv4)
        self.assertEqual(addr.toOid(), ipv4_oid)

        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv4_oid)
        self.assertEqual(addr_len, ipv4_oid[0] + 1)
        self.assertEqual(str(addr), ipv4)
        self.assertEqual(addr.toOid(), ipv4_oid)

        # Try both IPv6 and non-bytes name.
        addrtype = addrtype_attr.type(addrtype_attr, "ipv6")
        self.assertEqual(addrtype, "ipv6")
        addr_attr.typeName = u"InetAddressIPv6"
        # Snimpy does not use leading zeroes.
        ipv6 = u'102:304:506:708:90a:b0c:d0e:f01'
        ipv6_oid = (16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x01)

        addr = addr_attr.type(addr_attr, ipv6)
        self.assertEqual(str(addr), ipv6)
        self.assertEqual(addr.toOid(), ipv6_oid)

        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv6_oid)
        self.assertEqual(addr_len, ipv6_oid[0] + 1)
        self.assertEqual(str(addr), ipv6)
        self.assertEqual(addr.toOid(), ipv6_oid)

        # Try a type from a different module (chosen because snmpwalk
        # prints IPv6 addresses incorrectly).
        ipv6_1xformat = u'1:2:3:4:5:6:7:8:9:a:b:c:d:e:f:1'
        addr_attr.typeName = "PhysAddress"

        addr = addr_attr.type(addr_attr, ipv6_1xformat)
        self.assertEqual(str(addr), ipv6_1xformat)
        self.assertEqual(addr.toOid(), ipv6_oid)

        # Try overriding back to the default.
        del addr_attr.typeName
        addr_len, addr = addr_attr.type.fromOid(addr_attr, ipv4_oid)
        self.assertEqual(bytes(addr), b"\x7f\0\0\1")
Пример #37
0
    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")
Пример #38
0
 def testOid(self):
     """Test OID basic type"""
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId",
                          mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assert_(isinstance(a, basictypes.Oid))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger"))
     self.assertEqual(a, mib.get("SNIMPY-MIB", "snimpyInteger").oid)
     # Suboid
     self.assert_((list(mib.get("SNIMPY-MIB", "snimpyInteger").oid) +
                   [2, 3]) in a)
     self.assert_((list(mib.get("SNIMPY-MIB", "snimpyInteger").oid)[:-1] +
                   [29, 3]) not in a)
     # Ability to extract a component
     self.assertEqual(a[0], 1)
     self.assertEqual(a[1], 3)
     self.assertEqual(a[-3], 45121)
     self.assertEqual(a[-1], 3)
     self.assertEqual(a[:3], (1, 3, 6))
     # Also accepts list
     a = basictypes.build("SNIMPY-MIB", "snimpyObjectId", (1, 2, 3, 4))
     self.assertEqual(a, (1, 2, 3, 4))
     self.assert_((1, 2, 3, 4, 5) in a)
     self.assert_((3, 4, 5, 6) not in a)
Пример #39
0
    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")
Пример #40
0
 def testOid(self):
     """Test that objects are rooted at the correct OID"""
     oids = {"snimpy": (1, 3, 6, 1, 2, 1, 45121),
             "snimpyScalars": (1, 3, 6, 1, 2, 1, 45121, 1),
             "snimpyString": (1, 3, 6, 1, 2, 1, 45121, 1, 2),
             "snimpyInteger": (1, 3, 6, 1, 2, 1, 45121, 1, 3),
             "snimpyBits": (1, 3, 6, 1, 2, 1, 45121, 1, 11),
             "snimpyTables": (1, 3, 6, 1, 2, 1, 45121, 2),
             "snimpySimpleTable": (1, 3, 6, 1, 2, 1, 45121, 2, 1),
             "snimpySimplePhys": (1, 3, 6, 1, 2, 1, 45121, 2, 1, 1, 4),
             "snimpyComplexTable": (1, 3, 6, 1, 2, 1, 45121, 2, 2),
             "snimpyComplexState": (1, 3, 6, 1, 2, 1, 45121, 2, 2, 1, 3),
             }
     for o in oids:
         self.assertEqual(mib.get('SNIMPY-MIB', o).oid, oids[o])
Пример #41
0
 def testOid(self):
     """Test that objects are rooted at the correct OID"""
     oids = {"snimpy": (1, 3, 6, 1, 2, 1, 45121),
             "snimpyScalars": (1, 3, 6, 1, 2, 1, 45121, 1),
             "snimpyString": (1, 3, 6, 1, 2, 1, 45121, 1, 2),
             "snimpyInteger": (1, 3, 6, 1, 2, 1, 45121, 1, 3),
             "snimpyBits": (1, 3, 6, 1, 2, 1, 45121, 1, 11),
             "snimpyTables": (1, 3, 6, 1, 2, 1, 45121, 2),
             "snimpySimpleTable": (1, 3, 6, 1, 2, 1, 45121, 2, 1),
             "snimpySimplePhys": (1, 3, 6, 1, 2, 1, 45121, 2, 1, 1, 4),
             "snimpyComplexTable": (1, 3, 6, 1, 2, 1, 45121, 2, 2),
             "snimpyComplexState": (1, 3, 6, 1, 2, 1, 45121, 2, 2, 1, 3),
             }
     for o in oids:
         self.assertEqual(mib.get('SNIMPY-MIB', o).oid, oids[o])
Пример #42
0
 def testVariousSet(self):
     """Set value of many types. This test should be monitored with a traffic capture"""
     mib.load(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           "SNIMPY-MIB.mib"))
     for oid, value in [('snimpyIpAddress', '10.14.12.12'),
                        ('snimpyInteger', 1574512),
                        ('snimpyEnum', 'testing'),
                        ('snimpyObjectId', (1,2,3,4,5,6)),
                        ('snimpyCounter', 545424),
                        ('snimpyGauge', 4857544),
                        ('snimpyTimeticks', timedelta(3, 18)),
                        ('snimpyBits', ["third", "last"])]:
         self.assertRaises(self.version == 1 and snmp.SNMPNoSuchName or snmp.SNMPNoAccess,
                           self.session.set,
                           mib.get('SNIMPY-MIB', oid).oid + (0,),
                           basictypes.build('SNIMPY-MIB', oid, value))
Пример #43
0
 def testVariousSet(self):
     """Set value of many types. This test should be monitored with a traffic capture"""
     mib.load(
         os.path.join(os.path.dirname(os.path.abspath(__file__)),
                      "SNIMPY-MIB.mib"))
     for oid, value in [('snimpyIpAddress', '10.14.12.12'),
                        ('snimpyInteger', 1574512),
                        ('snimpyEnum', 'testing'),
                        ('snimpyObjectId', (1, 2, 3, 4, 5, 6)),
                        ('snimpyCounter', 545424), ('snimpyGauge', 4857544),
                        ('snimpyTimeticks', timedelta(3, 18)),
                        ('snimpyBits', ["third", "last"])]:
         self.assertRaises(
             self.version == 1 and snmp.SNMPNoSuchName or snmp.SNMPNoAccess,
             self.session.set,
             mib.get('SNIMPY-MIB', oid).oid + (0, ),
             basictypes.build('SNIMPY-MIB', oid, value))
Пример #44
0
    def testTypeOverrides_Errors(self):
        table = mib.get("SNIMPY-MIB", "snimpyInetAddressTable")
        attr = table.index[1]

        # Value with the wrong type.
        self.assertRaises(AttributeError, setattr, attr, "typeName", None)

        # Unknown type.
        self.assertRaises(mib.SMIException, setattr, attr, "typeName",
                          "SomeUnknownType.kjgf")

        # Incompatible basetype.
        self.assertRaises(mib.SMIException, setattr, attr, "typeName",
                          "InetAddressType")

        # Parse error.
        attr.typeName = "InetAddressIPv4"
        self.assertRaises(ValueError, attr.type, attr, u"01:02:03:04")
Пример #45
0
    def testTypeOverrides_Errors(self):
        table = mib.get("SNIMPY-MIB", "snimpyInetAddressTable")
        attr = table.index[1]

        # Value with the wrong type.
        self.assertRaises(AttributeError, setattr, attr, "typeName", None)

        # Unknown type.
        self.assertRaises(mib.SMIException, setattr, attr, "typeName",
                          "SomeUnknownType.kjgf")

        # Incompatible basetype.
        self.assertRaises(mib.SMIException, setattr, attr, "typeName",
                          "InetAddressType")

        # Parse error.
        attr.typeName = "InetAddressIPv4"
        self.assertRaises(ValueError, attr.type, attr, u"01:02:03:04")
Пример #46
0
 def testTypes(self):
     """Test that we get the correct types"""
     tt = { "snimpyIpAddress": basictypes.IpAddress,
            "snimpyString": basictypes.String,
            "snimpyInteger": basictypes.Integer,
            "snimpyEnum": basictypes.Enum,
            "snimpyObjectId": basictypes.Oid,
            "snimpyBoolean": basictypes.Boolean,
            "snimpyCounter": basictypes.Unsigned32,
            "snimpyGauge": basictypes.Unsigned32,
            "snimpyTimeticks": basictypes.Timeticks,
            "snimpyCounter64": basictypes.Unsigned64,
            "snimpyBits": basictypes.Bits,
            "snimpySimpleIndex": basictypes.Integer,
            "snimpyComplexFirstIP": basictypes.IpAddress,
            "snimpyComplexSecondIP": basictypes.IpAddress,
            "snimpyComplexState": basictypes.Enum }
     for t in tt:
         self.assertEqual(mib.get('SNIMPY-MIB', t).type, tt[t])
Пример #47
0
 def testRanges(self):
     tt = {"snimpyIpAddress": 4,
           "snimpyString": (0, 255),
           "snimpyOctetString": None,
           "snimpyInteger": [(6, 18), (20, 23), (27, 1336)],
           "snimpyEnum": None,
           "snimpyObjectId": None,
           "snimpyBoolean": None,
           "snimpyCounter": (0, 4294967295),
           "snimpyGauge": (0, 4294967295),
           "snimpyTimeticks": (0, 4294967295),
           "snimpyCounter64": (0, 18446744073709551615),
           "snimpyBits": None,
           "snimpySimpleIndex": (1, 30),
           "snimpyComplexFirstIP": 4,
           "snimpyComplexSecondIP": 4,
           "snimpyComplexState": None
           }
     for t in tt:
         self.assertEqual(mib.get('SNIMPY-MIB', t).ranges, tt[t])
Пример #48
0
 def testRanges(self):
     tt = {"snimpyIpAddress": 4,
           "snimpyString": (0, 255),
           "snimpyOctetString": None,
           "snimpyInteger": [(6, 18), (20, 23), (27, 1336)],
           "snimpyEnum": None,
           "snimpyObjectId": None,
           "snimpyBoolean": None,
           "snimpyCounter": (0, 4294967295),
           "snimpyGauge": (0, 4294967295),
           "snimpyTimeticks": (0, 4294967295),
           "snimpyCounter64": (0, 18446744073709551615),
           "snimpyBits": None,
           "snimpySimpleIndex": (1, 30),
           "snimpyComplexFirstIP": 4,
           "snimpyComplexSecondIP": 4,
           "snimpyComplexState": None
           }
     for t in tt:
         self.assertEqual(mib.get('SNIMPY-MIB', t).ranges, tt[t])
Пример #49
0
 def testTypes(self):
     """Test that we get the correct types"""
     tt = {
         "snimpyIpAddress": basictypes.IpAddress,
         "snimpyString": basictypes.String,
         "snimpyInteger": basictypes.Integer,
         "snimpyEnum": basictypes.Enum,
         "snimpyObjectId": basictypes.Oid,
         "snimpyBoolean": basictypes.Boolean,
         "snimpyCounter": basictypes.Unsigned32,
         "snimpyGauge": basictypes.Unsigned32,
         "snimpyTimeticks": basictypes.Timeticks,
         "snimpyCounter64": basictypes.Unsigned64,
         "snimpyBits": basictypes.Bits,
         "snimpySimpleIndex": basictypes.Integer,
         "snimpyComplexFirstIP": basictypes.IpAddress,
         "snimpyComplexSecondIP": basictypes.IpAddress,
         "snimpyComplexState": basictypes.Enum
     }
     for t in tt:
         self.assertEqual(mib.get('SNIMPY-MIB', t).type, tt[t])
Пример #50
0
    def testMultipleThreads(self):
        """Test with multiple sessions in different threads."""
        count = 20
        agents = []
        for i in range(count):
            agents.append(
                self.addAgent('community{0}'.format(i),
                              'community{0}-authpass'.format(i),
                              'community{0}-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{0}'.format(i))
            session = snmp.Session(**params)
            session.timeout = 10 * 1000 * 1000
            oid, a = session.get(ooid)[0]
            exp = ("Snimpy Test Agent community{0}".format(i)).encode('ascii')
            with lock:
                if oid == ooid and \
                   a == exp:
                    successes.append("community{0}".format(i))
                else:
                    failures.append("community{0}".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{0}".format(i) for i in range(count)]))
Пример #51
0
    def testMultipleThreads(self):
        """Test with multiple sessions in different threads."""
        count = 20
        agents = []
        for i in range(count):
            agents.append(self.addAgent('community{0}'.format(i),
                                        'community{0}-authpass'.format(i),
                                        'community{0}-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{0}'.format(i))
            session = snmp.Session(**params)
            session.timeout = 10 * 1000 * 1000
            oid, a = session.get(ooid)[0]
            exp = ("Snimpy Test Agent community{0}".format(i)).encode('ascii')
            with lock:
                if oid == ooid and \
                   a == exp:
                    successes.append("community{0}".format(i))
                else:
                    failures.append("community{0}".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{0}".format(i)
                                 for i in range(count)]))
Пример #52
0
 def testGetNext(self):
     """Get next value"""
     ooid = mib.get('SNMPv2-MIB', 'sysDescr').oid
     oid, a = self.session.getnext(ooid)[0]
     self.assertEqual(oid, ooid + (0, ))
     self.assertEqual(a, " ".join(os.uname()))
Пример #53
0
 def call():
     mib.get('SNIMPY-MIB', 'snimpySimpleTable').type
Пример #54
0
 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")
Пример #55
0
 def testGetInteger(self):
     """Get an integer value"""
     oid, a = self.session.get(mib.get('IF-MIB', 'ifNumber').oid + (0,))[0]
     self.assert_(a > 1)     # At least lo and another interface
Пример #56
0
 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")
Пример #57
0
    def node_to_oid(self, mibtosearch, node):

        # see https://github.com/vincentbernat/snimpy/issues/85
        oid_tuple = mib.get(mibtosearch, node).oid
        oid_str = '.'.join(map(str, oid_tuple))
        return oid_str
Пример #58
0
 def testFmt(self):
     """Check that we get FMT from types"""
     self.assertEqual(mib.get("SNIMPY-MIB", 'snimpySimplePhys').fmt, "1x:")
     self.assertEqual(mib.get("SNIMPY-MIB", 'snimpyInteger').fmt, "d-2")
Пример #59
0
 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))