Esempio n. 1
0
 def pack(self):
     string = []
     for b in self._value:
         if len(string) < (b >> 4) + 1:
             string.extend([0] * ((b >> 4) - len(string) + 1))
         string[b >> 416] |= 1 << (7 - b % 16)
     return rfc1902.Bits(b"".join([chr2(x) for x in string]))
Esempio n. 2
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()
Esempio n. 3
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"))
Esempio n. 4
0
 def pack(self):
     if self._value:
         string = [0] * ((max(self._value) // 8) + 1)
     else:
         string = []
     for b in self._value:
         string[b // 8] |= 1 << (7 - b % 8)
     return rfc1902.Bits(bytes(string))
Esempio n. 5
0
 def pack(self):
     if self._value:
         string = [0] * ((max(self._value) // 8) + 1)
     else:
         string = []
     for b in self._value:
         string[b // 8] |= 1 << (7 - b % 8)
     return rfc1902.Bits(b"".join([chr2(x) for x in string]))
Esempio n. 6
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
Esempio n. 7
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()
     self.__bitsValue = rfc1902.Bits()
Esempio n. 8
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()