Ejemplo n.º 1
0
def snmpGet(host, oid):
    session = netsnmp.Session(Version=2,
                              DestHost=host,
                              Community=snmp_community)

    results_objs = netsnmp.VarList(netsnmp.Varbind(oid))
    session.get(results_objs)
    return results_objs
Ejemplo n.º 2
0
    def getVarList(self):
        # https://github.com/haad/net-snmp/blob/master/python/netsnmp/client.py#L107 - search for append
        varList = netsnmp.VarList()
        for key in self.subOIDs:
            appendOid = self.mainOID + '.' + key                       
            varList.append(netsnmp.Varbind(appendOid))            

        return varList
Ejemplo n.º 3
0
 def vlanSnooping_get_Enable(self, type='IGMP', vid=1):
     index = self.__getvlanSnoopingIndex(type, vid)
     pEn = netsnmp.Varbind(self.tnVlanIpmcSnoopingEnabled[0], index)
     vars = netsnmp.VarList(pEn)
     res = self.sess.get(vars)
     # if (res == 1):
     for var in vars:
         return var
Ejemplo n.º 4
0
def GetSNMPData(IP, oid, community, VLAN):
    #Create SNMP session with device IP and return SNMP Data as list of the objects
    SNMPData = netsnmp.VarList(netsnmp.Varbind(oid))
    session = netsnmp.Session(DestHost=IP,
                              Version=2,
                              Community=community + VLAN)
    session.walk(SNMPData)
    return SNMPData
Ejemplo n.º 5
0
 def setLocation(self, location):
     '''
     Changes the location of a router.
     '''
     self.retrieveLocation()
     self.syslocation.val = location
     varlist = netsnmp.VarList(self.syslocation)
     self.session.set(varlist)
Ejemplo n.º 6
0
def attempt_walk_data(session, oid):
    tag = []
    var = netsnmp.Varbind(oid)
    varl = netsnmp.VarList(var)
    data = list(session.walk(varl))
    for x in range(0, len(data)):
        tag.append(varl[x].tag)
    return data, tag
Ejemplo n.º 7
0
 def setContact(self, contact):
     '''
     Changes the contact of a router.
     '''
     self.retrieveContact()
     self.syscontact.val = contact
     varlist = netsnmp.VarList(self.syscontact)
     self.session.set(varlist)
Ejemplo n.º 8
0
 def setHostname(self, hostname):
     '''
     Changes the hostname of a router.
     '''
     self.retrieveHostname()
     self.sysname.val = hostname
     varlist = netsnmp.VarList(self.sysname)
     self.session.set(varlist)
def get_data(session, oid, helper):
    var = netsnmp.Varbind(oid)
    varl = netsnmp.VarList(var)
    data = session.get(varl)
    value = data[0]
    if not value:
        helper.exit(summary="snmpget failed - no data for host " + session.DestHost + " OID: " +oid, exit_code=unknown, perfdata='')
    return value
Ejemplo n.º 10
0
 def query(self, oid):
     try:
         oid = netsnmp.Varbind(oid)
         oidList = netsnmp.VarList(oid)
         result = self.session.walk(oidList)
     except Exception, err:
         print err
         result = None
Ejemplo n.º 11
0
 def retrieveCDPneighbors(self):
     '''
     Returns two lists about a router's cdp neighbors.
     '''
     cdpdeviceport = netsnmp.Varbind('.1.3.6.1.4.1.9.9.23.1.2.1.1.7')
     cdpdeviceid = netsnmp.Varbind('.1.3.6.1.4.1.9.9.23.1.2.1.1.6')
     idvarlist = netsnmp.VarList(cdpdeviceid)
     portvarlist = netsnmp.VarList(cdpdeviceport)
     self.session.walk(idvarlist)
     self.session.walk(portvarlist)
     portlist = []
     idlist = []
     for x in idvarlist:
         idlist.append(x.val)
     for x in portvarlist:
         portlist.append(x.val)
     return idlist, portlist
Ejemplo n.º 12
0
def getOid(oid):
	session = netsnmp.Session( DestHost=cmIP, Version=2, Community='private' )
	vars = netsnmp.VarList( netsnmp.Varbind(oid) )
	#print( session.get(vars) )
	value  = ( session.get(vars) )
	value =str(value)
	value = value.replace("(","") ; value = value.replace(")","") ; value = value.replace("'","") ; value = value.replace(",","") ## Clean up the string
	return  value
Ejemplo n.º 13
0
def varlist(oid):
    """consumes a list or a single oid, returns a Varlist"""
    varbinds = []
    if oid is list:
        varbinds = (netsnmp.VarBind(e) for e in oid)
    else:
        varbinds = [netsnmp.Varbind(oid)]
    return netsnmp.VarList(*varbinds)
Ejemplo n.º 14
0
 def retrieveUptime(self):
     '''
     Returns the uptime of a router.
     '''
     sysuptime = netsnmp.Varbind('.1.3.6.1.2.1.1.3.0')
     varlist = netsnmp.VarList(sysuptime)
     self.session.get(varlist)
     return sysuptime.val
Ejemplo n.º 15
0
def fetchOID(host, community, graphiteroot, emcFan, verbose):

    if verbose:
        print >> sys.stderr, 'connecting to host: %s using community: %s' % ( host, community )

    statsTable = {
        'fanSpeed': '1.3.6.1.4.1.12124.2.53.1.4'
        }
    snmp = netsnmp.Session(DestHost=host, Version=2, Community=community)

    # connect and fetch the list of isilon disks
    emcFanList = '.1.3.6.1.4.1.12124.2.53.1.2'
    Var = netsnmp.Varbind(emcFanList)
    Vars = netsnmp.VarList(Var)
    snmp.walk(Vars)
    currentTime = time.time()
    for vs in Vars:
        # vs.iid = the index of the zone
        # vs.tag = leaf identifier e.g. 'zone name
        # vs.val = name of virtual server
        # vs.type = snmp data type, e.g. counter, integer, etc

        # if we specified a list of zones
        # make sure we filter on those
        if emcFan:
            if vs.val not in emcFan:
                continue

        #import pdb;pdb.set_trace()
        for type in statsTable:
            try:
                oid = statsTable[type] + "." + vs.iid
                head, tail = oid.rsplit('.', 1)
                vars = netsnmp.VarList(netsnmp.Varbind(head, tail))
                result = [x[0] for x in snmp.get(vars)]
                result = float(x)
                if verbose:
                    print >> sys.stderr, '%s %s = %s' % (vs.val, type, result)
                #currentTime = time.time()
                datapoint = '%s.%s.%s' % (graphiteroot, vs.val.replace(' ',''), type)
                package.append((datapoint, (currentTime, result)))
            except Exception as uhoh:
                print >> sys.stderr, "could not get oid: %s" % uhoh
                #sys.exit(1)

    return package, currentTime, result
Ejemplo n.º 16
0
    def get_data(self, connection_info, metric):
        '''
        type connection_info: list of strings
        param connection_info: List [host, port, community]

        type task: list of strings
        param task: List [cpu | mem | la | net] io - not supported by snmp strategy

        return: dictionary { 
                'cpu':{
                        'user':1234,
                        'nice':1234,
                        ...}
                'la':{
                        'la1':0.1,
                        ...}
                'mem':{
                        'swap':12345,
                        ...}
                'net':{
                        'in':12345,
                        'out':12345}}
        '''

        host = connection_info[0]
        port = connection_info[1]
        community = connection_info[2]

        oids = []
        for metric_name in metric:
            oids += oids_data[metric_name].values()

        session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                                  Version=1,
                                  Community=community)
        Vars = netsnmp.VarList(*oids)

        snmp_data = dict(
            (oid, val) for oid, val in zip(oids, session.get(Vars)))

        def _convert_from_str(value):
            if type(value) is str:
                if '.' in value:
                    return float(value)
                else:
                    return int(value)
            else:
                return 'U'

        for oid, value in snmp_data.iteritems():
            snmp_data[oid] = _convert_from_str(value)

        data = {}
        for metric_name in metric:
            for metric in oids_data[metric_name].keys():
                data.setdefault(metric_name, {}).setdefault(
                    metric, snmp_data[oids_data[metric_name][metric]])
        return data
Ejemplo n.º 17
0
	def getBasicData(self,oltid):
		Serial = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuSerial, oltid))))
		RxPower = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuRxPower, oltid))))
		OnuID = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuID, oltid))))
		Status = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuStatus, oltid))))
		Profile = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuProfile, oltid))))
		Distance = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuDistance, oltid))))
		Model = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuModelName, oltid))))
		Uptime = self._snmp_session.walk (netsnmp.VarList (netsnmp.Varbind ("{}.{}".format (sleGponOnuLinkUpTime, oltid))))
		return Serial, RxPower, OnuID, Status, Profile, Distance, Model, Uptime
Ejemplo n.º 18
0
 def vclMacBasedVlan_setPort(self,mac='00:00:00:00:00:01',member='\x80'):
     """
     This function is used for modify the port member fot each mac-vlan item
     """
     index = '6.' + mac2index(mac)
     pMember = netsnmp.Varbind(self.tnVclMacBasedPortMember[0],index,member,getType(type=self.tnVclMacBasedPortMember[1]))
     vars = netsnmp.VarList(pMember)
     res = self.sess.set(vars)
     return res
Ejemplo n.º 19
0
    def testFunc(self):
        """HexStringGetNext"""
        session = setup_v2()

        varlist = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.6.3.10'))
        session.walk(varlist)
        for var in varlist:
            print(var)
        self.assertEqual(varlist[0].iid, '0')
Ejemplo n.º 20
0
    def test_v1_set_2(self):
        print("\n")
        print("---v1 set2-------------------------------------\n")

        sess = setup_v1()
        varlist = netsnmp.VarList(
            netsnmp.Varbind('sysLocation', '0', 'my newer location'))
        res = sess.set(varlist)
        print("v1 sess.set result: ", res, "\n")
Ejemplo n.º 21
0
def getServiceTag(hst, com):
    oid = netsnmp.VarList(
        netsnmp.Varbind('.1.3.6.1.4.1.674.10892.1.300.10.1.11'))
    res = netsnmp.snmpwalk(oid, Version=2, DestHost=hst, Community=com)
    if str(res) != "()":
        return res
    else:
        print "Couldn't read snmp value"
        sys.exit(3)
Ejemplo n.º 22
0
def count_timeouts(table_segment_head):

    # timeouts are always at element ".2.0" below the table segment head
    timeouts = ss.get(
        netsnmp.VarList(netsnmp.Varbind(table_segment_head + ".2.0")))
    _log.debug("Got value {} for timeout OID {}.2.0".format(
        timeouts[0], table_segment_head))

    return int(timeouts[0])
Ejemplo n.º 23
0
        def __init__(self, DestHost):
            self.log = lib_Log.Log(PrintToConsole=True)
            self.Error = False                
            self.log.increaseLevel()                
            self.destHost = DestHost

            #new from here
            self.community = 'public'
            self.remotePort = 161
            self.snmpVersion = 2 #2 => 2c

            self.tables = {}
            
            self.snmpSession = netsnmp.Session(Version=self.snmpVersion,
                                                DestHost=self.destHost, 
                                                Community=self.community,
                                                RemotePort = self.remotePort,
                                                Timeout = 500000, #micro-sec
                                                Retries = 2,
                                                UseNumeric = 1,  #using OIDs                                                                                          
                                                )

            
            self.oidConversion = {}
                                     

            self.textualConversion = {}
            self.textualConversion['ifMib_ifAdminStatus']                           = {1 : 'up',    2: 'down',  3: 'testing'    }
            self.textualConversion['ifMib_ifOperStatus']                            = {1 : 'up',    2: 'down',  3: 'testing',   4: 'unknown',   5: 'dormant',   6: 'notPresent',    7: 'lowerLayerDown' }
            self.textualConversion['ifMib_IANAifType']                              = {1 : 'other', 6: 'ethernetCsmacd',        33: 'rs232',    53: 'propVirtual'     }
            self.textualConversion['PowerEthernetMib_pethPsePortAdminEnable']       = {1 : 'true',  2: 'false'    }
            self.textualConversion['PowerEthernetMib_pethPsePortDetectionStatus']   = {1 : 'disabled',          2: 'searching', 3: 'deliveringPower', 4: 'fault', 5: 'test', 6: 'otherFault'}
            self.textualConversion['PowerEthernetMib_pethMainPseOperStatus']        = {1 : 'on',    2: 'off',  3: 'faulty'    }
            self.textualConversion['EntityMib_entPhysicalClass']                    = {1: 'other', 2: 'unkown', 3: 'chassis', 4: 'backplane', 5: 'container', 6: 'powerSupply', 7: 'fan', 8: 'sensor', 9: 'module', 10: 'port', 11: 'stack', 12: 'cpu'}
            self.textualConversion['QBridgeMib_dot1qVlanStatus']                    = {1: 'other', 2: 'permanent', 3: 'dynamicGvrp'}

            #general SNMPv2MIB definition
            self.oidConversion.update({
                                '.1.3.6.1.2.1.1.1' : {'name': 'sysDescr'},
                                '.1.3.6.1.2.1.1.2' : {'name': 'sysObjectID'},
                                '.1.3.6.1.2.1.1.3' : {'name': 'sysUptime'},
                                '.1.3.6.1.2.1.1.4' : {'name': 'sysContact'},
                                '.1.3.6.1.2.1.1.5' : {'name': 'sysName'},
                                '.1.3.6.1.2.1.1.6' : {'name': 'sysLocation'},
                                '.1.3.6.1.2.1.1.7' : {'name': 'sysServices'},
                            })
                             
            self.SNMPv2MIB_varList = netsnmp.VarList(
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.1'),
                                                        #netsnmp.Varbind('.1.3.6.1.2.1.1.2'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.3'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.4'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.5'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.6'),
                                                        #netsnmp.Varbind('.1.3.6.1.2.1.1.7'),                                                        
                                                        )
Ejemplo n.º 24
0
    def get(connection_info, metrics):
        """
        :type connection_info: dictionary 
        :param connection_info: {'host':host, 'port':port, 'community':community}

        :type metrics: list of strings
        :param metrics: list ['cpu', 'mem', 'la', 'net', 'io']

        :rtype: dictionary
        :returns: { 
                'cpu':{
                        'user':value,
                        'nice':value,
                        ...}
                'la':{
                        'la1':value,
                        ...}
                'mem':{
                        'swap':value,
                        ...}
                'net':{
                        'in':value,
                        'out':value}}
        """

        host = connection_info['host']
        port = connection_info['port']
        community = connection_info['community']

        oids = []
        for k, v in oids_data.iteritems():
            if k in metrics:
                for kk, vv in v.iteritems():
                    oids.append(vv)

        session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                                  Version=1,
                                  Community=community,
                                  Timeout=1000000)
        Vars = netsnmp.VarList(*oids)

        snmp_data = dict(
            (oid, val) for oid, val in zip(oids, session.get(Vars)))

        data = {}
        for metric_name in metrics:
            if metric_name not in oids_data:
                continue
            for metric in oids_data[metric_name].keys():
                try:
                    value = float(snmp_data[oids_data[metric_name][metric]])
                except Exception:
                    value = None
                data.setdefault(metric_name, {}).setdefault(metric, value)

        return data
Ejemplo n.º 25
0
def do_snmpquery(snmpcmd, oid_to_get, snmpget):
    """Do an SNMP query
 
    Args:
        snmpcmd: SNMP variables required to do SNMP queries on device
        oid_to_get: OID to walk
        snmpget: Flag determining whether to do a GET or WALK
 
    Returns:
        Dictionary of tuples (OID, value)
    """
 
    # Initialize variables
    return_results = {}
    results_objs = False
    session = False
 
    # Get OID
    try:
        session = netsnmp.Session(DestHost=snmpcmd['ipaddress'],
            Version=snmpcmd['version'], Community=snmpcmd['community'],
            SecLevel='authPriv', AuthProto=snmpcmd['authprotocol'],
            AuthPass=snmpcmd['authpassword'], PrivProto=snmpcmd['privprotocol'],
            PrivPass=snmpcmd['privpassword'], SecName=snmpcmd['secname'],
            UseNumeric=True)
        results_objs = netsnmp.VarList(netsnmp.Varbind(oid_to_get))
 
        if snmpget:
            session.get(results_objs)
        else:
            session.walk(results_objs)
 
    except Exception as exception_error:
    # Check for errors and print out results
        print ('ERROR: Occurred during SNMPget for OID %s from %s: '
               '(%s)') % (oid_to_get, snmpcmd['ipaddress'], exception_error)
        sys.exit(2)
 
    # Crash on error
    if (session.ErrorStr):
        print ('ERROR: Occurred during SNMPget for OID %s from %s: '
               '(%s) ErrorNum: %s, ErrorInd: %s') % (
                oid_to_get, snmpcmd['ipaddress'], session.ErrorStr,
                session.ErrorNum, session.ErrorInd)
        sys.exit(2)
 
    # Construct the results to return
    for result in results_objs:
        if is_number(result.val):
            return_results[('%s.%s') % (result.tag, result.iid)] = (
                float(result.val))
        else:
            return_results[('%s.%s') % (result.tag, result.iid)] = (
                result.val)
 
    return return_results
 def testsnmpgethmmbladetable(self):
     '''snmp get hmmbladetable'''
     snmpvars = netsnmp.VarList(
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.82.1.82.4.1.8.0'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.82.1.82.4.1.20.0'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.82.1.82.4.1.32.0'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.82.1.82.4.1.57.0'))
     vals = self.sess.get(snmpvars)
     print vals
     self.assertIsNotNone(vals)
Ejemplo n.º 27
0
 def testsnmpgetharddisktable(self):
     '''snmp get harddisktable'''
     snmpvars = netsnmp.VarList(
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.18.50.1.1.1'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.18.50.1.2.1'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.18.50.1.3.1'),
         netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.18.50.1.4.1'))
     vals = self.sess.get(snmpvars)
     print vals
     self.assertIsNotNone(vals)
Ejemplo n.º 28
0
def get_values(table):
    """
        Function that returns the values especified in a table
    @arg table - the table from which we want the values
    @return - a list containing every value
    """
    global SESSION
    result = netsnmp.Varbind(table)
    resultlist = netsnmp.VarList(result)
    return SESSION.walk(resultlist)
Ejemplo n.º 29
0
def get_next(value):
    """
        Function that returns the values especified in a element
    @arg value - the value from which we want the result
    @return - a list containing this result
    """
    global SESSION
    result = netsnmp.Varbind(value)
    resultlist = netsnmp.VarList(result)
    return SESSION.get(resultlist)[0]
Ejemplo n.º 30
0
    def test_v3_set(self):
        print("\n")
        print("---v3 set-------------------------------------\n")

        sess = setup_v3()
        varlist = netsnmp.VarList(
            netsnmp.Varbind('sysLocation', '0', 'my final destination'))
        res = sess.set(varlist)
        print("v3 sess.set result: ", res, "\n")
        self.assertEqual(res, 1)