Пример #1
0
 def update_time_on_battery(self, timeticks):
     """Update OIDs associated with UPS time on battery
     
     Args:
         timeticks(int): time-on battery (seconds*100)
     """
     self._update_oid_by_name("TimeOnBattery", snmp_data_types.TimeTicks(timeticks))
Пример #2
0
 def testPacking(self):
     """Test pack() function"""
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyString",
                                       "Hello world").pack(),
                      rfc1902.OctetString("Hello world"))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyInteger",
                                       18).pack(),
                      rfc1902.Integer(18))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyInteger",
                                       1804).pack(),
                      rfc1902.Integer(1804))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyEnum",
                                       "testing").pack(),
                      rfc1902.Integer(3))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyIpAddress",
                                       "10.11.12.13").pack(),
                      rfc1902.IpAddress("10.11.12.13"))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyObjectId",
                                       (1, 2, 3, 4)).pack(),
                      rfc1902.univ.ObjectIdentifier((1, 2, 3, 4)))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyTimeticks",
                                       timedelta(3, 2)).pack(),
                      rfc1902.TimeTicks(3 * 3600 * 24 * 100 + 2 * 100))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyBits",
                                       [1, 7]).pack(),
                      rfc1902.Bits(b"\x41"))
Пример #3
0
    def __init__(self, mibViewController):
        if 'PYSNMPOIDPREFIX' in os.environ:
            self.DEFAULT_OID_PREFIX = os.environ['PYSNMPOIDPREFIX']

        if 'PYSNMPMIBS' in os.environ:
            self.DEFAULT_MIBS = os.environ['PYSNMPMIBS'].split(os.pathsep)

        if 'PYSNMPMIBDIRS' in os.environ:
            self.DEFAULT_MIB_DIRS = os.environ['PYSNMPMIBDIRS'].split(
                os.pathsep)

        if self.DEFAULT_MIB_DIRS:
            mibViewController.mibBuilder.setMibSources(
                *(mibViewController.mibBuilder.getMibSources() + tuple([
                    builder.ZipMibSource(m).init()
                    for m in self.DEFAULT_MIB_DIRS
                ])))

        if self.DEFAULT_MIBS:
            mibViewController.mibBuilder.loadModules(*self.DEFAULT_MIBS)

        self.__oidValue = univ.ObjectIdentifier()
        self.__intValue = univ.Integer()
        self.__timeValue = rfc1902.TimeTicks()
        self.__bitsValue = rfc1902.Bits()
Пример #4
0
 def __init__(self, mibViewController, lock):
     self.__lock = lock
     self.__oidValue = univ.ObjectIdentifier()
     self.__intValue = univ.Integer()
     self.__timeValue = rfc1902.TimeTicks()
     self.__mib_view = mibViewController
     return
Пример #5
0
    def __coerce_value(initial_value, new_value):
        """Coerce the new_value to the same type as the initial_value.

        :param initial_value: initial value from the device
        :param new_value: new value to set, coerced into the right type
        :return: new value, coerced into the right type
        """
        # pylint: disable=redefined-variable-type
        # In order to return the right type the return value has to be
        # redefined.

        # Types from RFC-1902
        if isinstance(initial_value, rfc1902.Counter32):
            set_value = rfc1902.Counter32(str(new_value))
        elif isinstance(initial_value, rfc1902.Counter64):
            set_value = rfc1902.Counter64(str(new_value))
        elif isinstance(initial_value, rfc1902.Gauge32):
            set_value = rfc1902.Gauge32(str(new_value))
        elif isinstance(initial_value, rfc1902.Integer):
            set_value = rfc1902.Integer(str(new_value))
        elif isinstance(initial_value, rfc1902.Integer32):
            set_value = rfc1902.Integer32(str(new_value))
        elif isinstance(initial_value, rfc1902.IpAddress):
            set_value = rfc1902.IpAddress(str(new_value))
        elif isinstance(initial_value, rfc1902.OctetString):
            set_value = rfc1902.OctetString(str(new_value))
        elif isinstance(initial_value, rfc1902.TimeTicks):
            set_value = rfc1902.TimeTicks(str(new_value))
        elif isinstance(initial_value, rfc1902.Unsigned32):
            set_value = rfc1902.Unsigned32(str(new_value))
        else:
            raise RuntimeError("Unknown type %s" % type(initial_value))

        return set_value
Пример #6
0
    def update_time_left(self, timeticks):
        """Update OIDs associated with UPS runtime
        (estimation of how long UPS will be operating)

        Args:
            timeticks(int): time left
        """
        self._update_oid_by_name("BatteryRunTimeRemaining",
                                 snmp_data_types.TimeTicks(timeticks))
Пример #7
0
    def snmpset(self,*args):
        '''This api is used for oid snmpset operation'''
	self.snmp_target = (self.host,self.snmp_port)
	cg = cmdgen.CommandGenerator()
	comm_data = cmdgen.CommunityData('my-manager', self.community_string)
	transport = cmdgen.UdpTransportTarget(self.snmp_target)
	snmpset_data = []
	for i in range(len(args[0])):
	    print("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n")
	    snmpset_data.append("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n")
	    print("<<<<<<<<OUTPUT>>>>>>>>>")
            snmpset_data.append("<<<<<<<<OUTPUT>>>>>>>>>")
	    if args[0][i][2] == "s":
	          variables = (args[0][i][0], rfc1902.OctetString(args[0][i][1]))
	          errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    elif args[0][i][2] == "i":
	          variables = (args[0][i][0], rfc1902.Integer(args[0][i][1]))
	          errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    elif args[0][i][2] == "o":
	          variables = (args[0][i][0], rfc1902.Bits(args[0][i][1]))
                  errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    elif args[0][i][2] == "t":
	          variables = (args[0][i][0], rfc1902.TimeTicks(args[0][i][1]))
                  errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    elif args[0][i][2] == "u":
	          variables = (args[0][i][0], rfc1902.Unsigned32(args[0][i][1]))
                  errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    elif args[0][i][2] == "ip":
	          variables = (args[0][i][0], rfc1902.IpAddress(args[0][i][1]))
                  errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
   	          snmpset_data.append(result)
	    elif args[0][i][2] == "U":
	          variables = (args[0][i][0], rfc1902.Gauge32(args[0][i][1]))
                  errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables)
	          snmpset_data.append(result)
	    else:
	         pass

      	# Check for errors and print out results
	if errIndication:
	    print(errIndication)
	    snmpset_data.append(errIndication)
	elif errStatus:
	    print("REASON :" + '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?'))
	    snmpset_data.append("REASON : "+ '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?'))
	else:
	    for name, val in result:
	        print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
		snmpset_data.append(name.prettyPrint() +" = "+ val.prettyPrint())	
        return snmpset_data
Пример #8
0
class __WritePduGenerator(__ReadPduGenerator):
    _typeMap = {
        'i': rfc1902.Integer(),
        'u': rfc1902.Integer32(),
        's': rfc1902.OctetString(),
        'n': univ.Null(),
        'o': univ.ObjectIdentifier(),
        't': rfc1902.TimeTicks(),
        'a': rfc1902.IpAddress()
    }

    def n_VarType(self, cbCtx, node):
        snmpEngine, ctx = cbCtx
        ctx['varType'] = node[0].attr

    def n_VarValue(self, cbCtx, node):
        snmpEngine, ctx = cbCtx
        ctx['varValue'] = node[0].attr

    def n_VarBind_exit(self, cbCtx, node):
        snmpEngine, ctx = cbCtx
        mibViewCtl = ctx['mibViewController']
        if ctx['varType'] == '=':
            modName, nodeDesc, suffix = mibViewCtl.getNodeLocation(
                ctx['varName'])
            mibNode, = mibViewCtl.mibBuilder.importSymbols(modName, nodeDesc)
            if hasattr(mibNode, 'syntax'):
                MibTableColumn, = mibViewCtl.mibBuilder.importSymbols(
                    'SNMPv2-SMI', 'MibTableColumn')
                if isinstance(mibNode, MibTableColumn) or suffix == (0, ):
                    val = mibNode.syntax
                else:
                    raise error.PySnmpError(
                        'Found MIB scalar %s but non-scalar given %s' %
                        (mibNode.name + (0, ), ctx['varName']))
            else:
                raise error.PySnmpError('Variable %s has no syntax' %
                                        (ctx['varName'], ))
        else:
            try:
                val = self._typeMap[ctx['varType']]
            except KeyError:
                raise error.PySnmpError('unsupported SNMP value type \"%s\"' %
                                        ctx['varType'])
        try:
            val = val.clone(ctx['varValue'])
        except PyAsn1Error:
            raise error.PySnmpError(sys.exc_info()[1])

        if 'varBinds' not in ctx:
            ctx['varBinds'] = [(ctx['varName'], val)]
        else:
            ctx['varBinds'].append((ctx['varName'], val))
Пример #9
0
 def __init__(self, mibViewController):
     if 'PYSNMPOIDPREFIX' in os.environ:
         self.defaultOidPrefix = os.environ['PYSNMPOIDPREFIX']
     if 'PYSNMPMIBS' in os.environ:
         self.defaultMibs = os.environ['PYSNMPMIBS'].split(':')
     if 'PYSNMPMIBDIRS' in os.environ:
         self.defaultMibDirs = os.environ['PYSNMPMIBDIRS'].split(':')
     if self.defaultMibDirs:
         mibViewController.mibBuilder.setMibSources(
             *(mibViewController.mibBuilder.getMibSources() + tuple([
                 builder.ZipMibSource(m).init() for m in self.defaultMibDirs
             ])))
     if self.defaultMibs:
         mibViewController.mibBuilder.loadModules(*self.defaultMibs)
     self.__oidValue = univ.ObjectIdentifier()
     self.__intValue = univ.Integer()
     self.__timeValue = rfc1902.TimeTicks()
Пример #10
0
 def _to_pysnmp(self, value):
     """ Convert connection plugin object into pysnmp objects """
     if value is None:
         return None
     if isinstance(value, OctetString):
         return rfc1902.OctetString(str(value.value))
     if isinstance(value, ObjectIdentifier):
         return rfc1902.ObjectName(str(value.value))
     if isinstance(value, Integer32):
         return rfc1902.Integer32(int(value.value))
     if isinstance(value, Counter32):
         return rfc1902.Counter32(long(value.value))
     if isinstance(value, IpAddress):
         return rfc1902.IpAddress(str(value.value))
     if isinstance(value, Gauge32):
         return rfc1902.Gauge32(long(value.value))
     if isinstance(value, TimeTicks):
         return rfc1902.TimeTicks(long(value.value))
     if isinstance(value, Opaque):
         return rfc1902.Opaque(value.value)  # FIXME
     if isinstance(value, Counter64):
         return rfc1902.Counter64(str(value.value))
     raise SnmpError('Invalid type: %s' % value.__class__.__name__)
Пример #11
0
            expect(snmp_value.value()).to(equal(42))
            expect(snmp_value.type_text()).to(equal('Gauge32'))

    with context('when type is ObjectIdentifier'):
        with it('checks value and type'):
            snmp_data = univ.ObjectIdentifier('1.1')

            snmp_value = PySnmpValue(snmp_data)

            expect(snmp_value.value()).to(equal('1.1'))
            expect(snmp_value.type_text()).to(equal('ObjectIdentifier'))

    with context('when type is not recognized'):
        with it('value is None'):
            snmp_data = rfc1902.TimeTicks(42)

            snmp_value = PySnmpValue(snmp_data)

            expect(snmp_value.value()).to(equal(None))

with description('SNMP Types'):
    with context('when type is Integer'):
        with it('checks that value is an instance of Integer'):
            snmp_value = PySnmpTypes().integer(5)

            expect(snmp_value).to(be_a(pysnmp.proto.rfc1902.Integer))

    with context('when type is Integer32'):
        with it('checks that value is an instance of Integer32'):
            snmp_value = PySnmpTypes().integer32(5)
Пример #12
0
 def pack(self):
     return rfc1902.TimeTicks(int(self))
Пример #13
0
    snmpEngine,
    # Notification targets
    'my-notification',
    # Default SNMP context where contextEngineId == SnmpEngineId
    context.SnmpContext(snmpEngine),
    # contextName
    '',
    # notification name: Generic Trap #6 (enterpriseSpecific)
    #                    and Specific Trap 432
    '1.3.6.1.4.1.20408.4.1.1.2.0.432',
    # notification objects instance index
    None,
    # additional var-binds holding SNMPv1 TRAP details
    [
        # Uptime value with 12345
        (rfc1902.ObjectName('1.3.6.1.2.1.1.3.0'), rfc1902.TimeTicks(12345)),
        # Agent Address with '127.0.0.1'
        (rfc1902.ObjectName('1.3.6.1.6.3.18.1.3.0'),
         rfc1902.IpAddress('127.0.0.1')),
        # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2
        (rfc1902.ObjectName('1.3.6.1.6.3.1.1.4.3.0'),
         rfc1902.ObjectName('1.3.6.1.4.1.20408.4.1.1.2')),
        # managed object '1.3.6.1.2.1.1.1.0' = 'my system'
        (rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'),
         rfc1902.OctetString('my system'))
    ]))

# Since SNMP TRAP's are unacknowledged, there's nothing to wait for. So we
# simulate other loop activities by sleep()'ing.
loop.run_until_complete(trollius.sleep(1))
 def convert_to_timeticks(self, value):
     """Converts a value to a SNMP TimeTicks object."""
     return rfc1902.TimeTicks(value)
Пример #15
0
    def set(self, name, value, instance=0, context=None, type='i'):
        '''
        snmpojb.set('swDetailsVersion', 1, '05.00.96')
        '''
        oid = ''
        if self.isDotNotation(name):
            oid = name
            # TODO do we try and guess what our value is if we are given dot notation
            #rfcValue=rfc1902.OctetString(value)
            # type can be:  i INTEGER, u  UNSIGNED, s  STRING, x  HEX STRING, d  DECIMAL STRING
            # n  NULLOBJ, o  OBJID, t  TIMETICKS, a  IPADDRESS, b  BITS
            assert (type in 'iusxdnotab'
                    ), "ERROR: Value type {0} not supported".format(type)
            try:
                if type == 'i':
                    rfcValue = rfc1902.Integer32(value)
                elif type == 'u':
                    rfcValue = rfc1902.Unsigned32(value)
                elif type == 't':
                    rfcValue = rfc1902.TimeTicks(value)
                elif type == 'a':
                    rfcValue = rfc1902.IpAddress(value)
                elif type == 'b':
                    rfcValue = rfc1902.Bits(value)
                elif type == 's':
                    rfcValue = rfc1902.OctetString(value)
                elif type == 'o':
                    rfcValue = univ.ObjectIdentifier(value)
                elif type in 'xdn':
                    print 'WARNING: Type ' + type + ' not fully supported (hope default will do)'
                    rfcValue = rfc1902.OctetString(value)
                else:
                    print "unknown type"
            except:
                print("Error in SNMPClient, could not convert {} to type {}"
                      ).format(value, type)
        else:
            oid = self.mibs[name].get('oid')
            # TODO: incode the type
            type = self.mibs[name].get('type')
            # TODO: do something similar as if a couple of lines up
            rfcValue = self.mibs.encode(type, value)
        #if instance!=0:
        oid += '.' + str(instance)

        if context == None:
            context = self.context

        if SNMPClient.DEBUG:
            print "Setting %s (%s) = %s" % (name, oid, str(value))
        cmdGen = MyCmdGen()
        errorIndication, errorStatus, _, varBinds = cmdGen.setCmd(
            self.agent, context, self.host, self.port,
            (rfc1902.ObjectName(oid), rfcValue))

        if SNMPClient.DEBUG:
            print 'agent', self.agent
            print 'context', context
            print 'host', self.host
            print 'port', self.port
            print 'type', type

        if errorIndication:
            raise IOError(errorIndication)
        if errorStatus:
            raise SNMPError('set on ' + oid + '(' + name + ')', errorStatus)

        return varBinds[-1][1].prettyPrint()
    udp.domainName, ('195.218.195.228', 161),
    'my-creds'
)

# Error/response receiver
def cbFun(sendRequestHandle,
          errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1][0] or '?'
            )
        )
    else:
        for oid, val in varBinds:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

# Prepare and send a request message
cmdgen.SetCommandGenerator().sendReq(
    snmpEngine,
    'my-router',
    ( ((1,3,6,1,2,1,1,9,1,4,1), rfc1902.TimeTicks(123)), ),
    cbFun
)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
Пример #17
0
#     SNMPv3 user 'usr-sha-aes', auth: SHA, priv: AES128
#     over IPv6/UDP
#     send TRAP notification
#     with TRAP ID 'authenticationFailure' specified as a MIB symbol
#     include managed object information 1.3.6.1.2.1.1.1.0 = 'my system'
#     include managed object information 1.3.6.1.2.1.1.3.0 = 567
errorIndication = ntfOrg.sendNotification(
    ntforg.UsmUserData('usr-sha-aes',
                       'authkey1',
                       'privkey1',
                       authProtocol=ntforg.usmHMACSHAAuthProtocol,
                       privProtocol=ntforg.usmAesCfb128Protocol),
    ntforg.Udp6TransportTarget(('::1', 162)), 'trap',
    ntforg.MibVariable('SNMPv2-MIB', 'authenticationFailure'),
    ('1.3.6.1.2.1.1.1.0', rfc1902.OctetString('my system')),
    ('1.3.6.1.2.1.1.3.0', rfc1902.TimeTicks(567)))

if errorIndication:
    print('Notification not sent: %s' % errorIndication)

# Using
#     SNMPv3 user 'usr-none-none', no auth, no priv
#     over IPv4/UDP
#     send TRAP notification
#     with TRAP ID 'authenticationFailure' specified as a MIB symbol
#     include managed object information 1.3.6.1.2.1.1.2.0 = 1.3.6.1.2.1.1.1
errorIndication = ntfOrg.sendNotification(
    ntforg.UsmUserData('usr-none-none'),
    ntforg.UdpTransportTarget(('localhost', 162)), 'trap',
    ntforg.MibVariable('SNMPv2-MIB', 'authenticationFailure'),
    ('1.3.6.1.2.1.1.2.0', rfc1902.ObjectName('1.3.6.1.2.1.1.1')))