Ejemplo n.º 1
0
    def test_leaves(self):
        """Testing function leaves."""
        #################################################
        # NOTE: Detailed OID and branch testing in
        # test_oid_valid_format and test_oid_branch_valid
        #################################################

        # Define key variables
        leaf = '1'
        branch = '.1.3.6.1.2.1.31.1.1.1.6'
        oid = '{}.{}'.format(branch, leaf)

        #################################################
        # Test invalid OID
        #################################################

        object2test = class_oid.OIDstring(self.generic_random_string)
        with self.assertRaises(SystemExit):
            object2test.leaves(branch)

        #################################################
        # Test invalid branch
        #################################################

        object2test = class_oid.OIDstring(oid)
        with self.assertRaises(SystemExit):
            object2test.leaves(self.generic_random_string)

        #################################################
        # Test valid data
        #################################################

        # Test with branch not in oid_type database
        fake_branch = '.9.3.6.1.2.1.31.1.1.1.6'
        object2test = class_oid.OIDstring(oid)
        result = object2test.leaves(fake_branch)
        self.assertEqual(result, None)

        # Single number leaf
        object2test = class_oid.OIDstring(oid)
        result = object2test.leaves(branch)
        self.assertEqual(result, '.{}'.format(leaf))

        # Multi-number leaf
        leaf = '1.34'
        oid = '{}.{}'.format(branch, leaf)
        object2test = class_oid.OIDstring(oid)
        result = object2test.leaves(branch)
        self.assertEqual(result, '.{}'.format(leaf))
Ejemplo n.º 2
0
    def test_node_y(self):
        """Testing function node_y."""
        # Define key variables
        oid = '.1.3.6.1.2.1.31.1.4.5.7'
        expected_value = 5

        #################################################
        # Test invalid OID
        #################################################

        object2test = class_oid.OIDstring(self.generic_random_string)
        with self.assertRaises(SystemExit):
            object2test.leaves(oid)

        #################################################
        # Test valid data
        #################################################

        object2test = class_oid.OIDstring(oid)
        self.assertEqual(object2test.node_y(), expected_value)
Ejemplo n.º 3
0
    def test_valid_format(self):
        """Testing function valid_format."""
        # Define key variables
        oid_no_dot = self.value['branch_no_dot']
        oid_end_dot = self.value['branch_end_dot']
        oid_mid_string = self.value['branch_mid_string']

        #################################################
        # Cannot be empty oid string
        #################################################

        object2test = class_oid.OIDstring('')
        self.assertEqual(object2test.valid_format(), False)

        #################################################
        # Cannot be blank oid
        #################################################

        object2test = class_oid.OIDstring('     ')
        self.assertEqual(object2test.valid_format(), False)

        #################################################
        # Cannot be oid with no leading '.'
        #################################################

        object2test = class_oid.OIDstring(oid_no_dot)
        self.assertEqual(object2test.valid_format(), False)

        #################################################
        # Cannot be oid with trailing '.'
        #################################################

        object2test = class_oid.OIDstring(oid_end_dot)
        self.assertEqual(object2test.valid_format(), False)

        #################################################
        # No non numeric strings between '.'
        #################################################

        object2test = class_oid.OIDstring(oid_mid_string)
        self.assertEqual(object2test.valid_format(), False)

        #################################################
        # Valid OID
        #################################################

        # Verify oid
        object2test = class_oid.OIDstring(self.value['fake_test_oid'])
        self.assertEqual(object2test.valid_format(), True)
Ejemplo n.º 4
0
 def test___init__(self):
     """Testing function __init__."""
     # Fail if class is instantiated with an invalid integer value. (-1)
     with self.assertRaises(SystemExit):
         class_oid.OIDstring(-1)
Ejemplo n.º 5
0
    def query(self,
              oid_to_get,
              get=False,
              check_reachability=True,
              check_existence=False,
              context_name=''):
        """Do an SNMP query.

        Args:
            oid_to_get: OID to walk
            get: Flag determining whether to do a GET or WALK
            check_reachability:
                Set if testing for connectivity. Some session
                errors are ignored so that a null result is returned
            check_existence:
                Set if checking for the existence of the OID
            context_name: Set the contextName used for SNMPv3 messages.
                The default contextName is the empty string "".  Overrides the
                defContext token in the snmp.conf file.

        Returns:
            Dictionary of tuples (OID, value)

        """
        # Initialize variables
        _contactable = True
        exists = True
        results = []

        # Create OID string object
        oid_string = class_oid.OIDstring(oid_to_get)

        # Check if OID is valid
        valid_format = oid_string.valid_format()
        if valid_format is False:
            log_message = ('OID {} has an invalid format'.format(oid_to_get))
            log.log2die(51449, log_message)

        # Create SNMP session
        session = _Session(self._snmpvariable,
                           context_name=context_name).session

        # Create failure log message
        try_log_message = (
            'Error occurred during SNMPget {}, SNMPwalk {} query against '
            'target {} OID {} for context "{}"'
            ''.format(get, not get, self._snmp_ip_target, oid_to_get,
                      context_name))

        # Fill the results object by getting OID data
        try:
            # Get the data
            if get is True:
                results = [session.get(oid_to_get)]

            else:
                if self._snmp_version != 1:
                    # Bulkwalk for SNMPv2 and SNMPv3
                    results = session.bulkwalk(oid_to_get,
                                               non_repeaters=0,
                                               max_repetitions=25)
                else:
                    # Bulkwalk not supported in SNMPv1
                    results = session.walk(oid_to_get)

        # Crash on error, return blank results if doing certain types of
        # connectivity checks
        except (exceptions.EasySNMPConnectionError,
                exceptions.EasySNMPTimeoutError,
                exceptions.EasySNMPUnknownObjectIDError,
                exceptions.EasySNMPNoSuchNameError,
                exceptions.EasySNMPNoSuchObjectError,
                exceptions.EasySNMPNoSuchInstanceError,
                exceptions.EasySNMPUndeterminedTypeError) as exception_error:

            # Update the error message
            try_log_message = ("""\
{}: [{}, {}, {}]""".format(try_log_message,
                           sys.exc_info()[0],
                           sys.exc_info()[1],
                           sys.exc_info()[2]))

            # Process easysnmp errors
            (_contactable,
             exists) = _process_error(try_log_message, exception_error,
                                      check_reachability, check_existence)

        except SystemError as exception_error:
            # Update the error message
            try_log_message = ("""\
{}: [{}, {}, {}]""".format(try_log_message,
                           sys.exc_info()[0],
                           sys.exc_info()[1],
                           sys.exc_info()[2]))

            # Process easysnmp errors
            (_contactable, exists) = _process_error(try_log_message,
                                                    exception_error,
                                                    check_reachability,
                                                    check_existence,
                                                    system_error=True)

        except:
            log_message = ('Unexpected error: {}, {}, {}, {}'
                           ''.format(sys.exc_info()[0],
                                     sys.exc_info()[1],
                                     sys.exc_info()[2], self._snmp_ip_target))
            log.log2die(51029, log_message)

        # Format results
        values = _convert_results(results)

        # Return
        return (_contactable, exists, values)