Beispiel #1
0
 def get_session(self, device=None, vlan=None, use_easysnmp=True):
     if not vlan:
         vlan = 0
         community = self.community
     else:
         vlan = int(vlan)
         community = self.community + '@' + str(vlan)
     if not device:
         if not self.device:
             raise ValueError('No device specified')
         device = self.device
     if device not in self.sessions or self.sessions[device] is None:
         self.sessions[device] = dict()
     if vlan not in self.sessions[device]:
         # print('Creating session for %s vlan %s community %s' %
         #        (device, vlan, community))
         if use_easysnmp:
             try:
                 self.sessions[device][vlan] = Session(
                     hostname=device,
                     community=community,
                     version=2,
                     abort_on_nonexistent=True,)
             except easysnmp.exceptions.EasySNMPConnectionError as exception:
                 raise ValueError('Unable to open session with %s vlan %s: %s'
                                  % (device, vlan, exception))
             except easysnmp.exceptions.EasySNMPTimeoutError as exception:
                 raise ValueError('Timeout connecting to %s: %s'
                                  % (device, exception))
         else:
             self.sessions[device][vlan] = netsnmp.SNMPSession(device, community, version=0)
     return self.sessions[device][vlan]
Beispiel #2
0
def public_resolv(sw_ip):
    retval = []
    device = {}
    with netsnmp.SNMPSession(sw_ip, 'public') as ss:
        discovery = [response for response in ss.walk([_OID])]
        for item in discovery:
            for row in item:
                if _OID in row:
                    device_str = row[_OID_offset:].split('.')
                    vlan = device_str[0]
                    mac = "%02x:%02x:%02x:%02x:%02x:%02x" % tuple(
                        int(i) for i in device_str[1:])
                    device['mac'] = mac
                    device['vlan'] = vlan
                    retval.append(device)
                    device = {}
    return retval
Beispiel #3
0
 def __init__(self, ip, community='public', version=0):
     import netsnmp
     self.session = netsnmp.SNMPSession(ip,
                                        community,
                                        version=version,
                                        timeout=0.1)
Beispiel #4
0
    def follow_mib( self,node_list,wait_time='10s',interval_time='5s',\
                    len='12',percentile='80',threshold='75',max_len='300',factor = '1'):
        """ Waits until all the nodes defined in ``node_list`` become ``stable``. 

        Stableness is checked by SNMP polling result. The MIB list is define by
        ``mib`` in ``node`` section
        Parameter:
        - ``wait_time(1)``: the time before the evaluation starting
        - ``interval_time(2)``: interval between SNMP polling time
        - ``threshold``: below this value is evaluated as ``stable`` 
        - ``len(3)``: the size of the evaluation window (number of values that
          are used in each valuation)
        - ``percentile``: real useful percentage of data (ignore top
          ``100-percentile`` percent)
        - ``max_len(4)``: maximum waiting ``lend`` for this checking
    
        | time sequence: --(1)--|-(2)-|-----|-----|----|-----|-----|
        |                      <--------(3)---------->     poll  poll 
        |                            <--------(3)----------> 
        |                      <---------------------(4)---------->
        
        """
        time.sleep(DateTime.convert_time(wait_time))

        interval = DateTime.convert_time(interval_time)
        data = {}
        for node in node_list:
            device = Common.LOCAL['node'][node]['device']
            type = Common.GLOBAL['device'][device]['type']
            data[node] = {}
            data[node]['ip'] = Common.GLOBAL['device'][device]['ip']
            data[node]['community'] = Common.GLOBAL['snmp-template'][type][
                'community']
            data[node]['mib_file'] = Common.mib_for_node(node)
            f = open(data[node]['mib_file'])
            data[node]['oid_list'] = json.load(f)['miblist']
            f.close()
            data[node]['poller'] = netsnmp.SNMPSession(data[node]['ip'],
                                                       data[node]['community'])
            data[node]['monitor'] = []

        for i in range(int(len)):
            for node in node_list:
                for oid in data[node]['oid_list']:
                    try:
                        value = float(data[node]['poller'].get(
                            oid['oid'])[0][2])
                    except:
                        value = 0.0
                    data[node]['monitor'].insert(0, value)
            time.sleep(interval)

        stable = False
        count = 0

        BuiltIn().log("Stable checking ...")

        while not stable and count < max_len:
            stable = True
            for node in node_list:
                for oid in data[node]['oid_list']:
                    try:
                        value = float(data[node]['poller'].get(
                            oid['oid'][0][2]))
                    except:
                        value = 0.0
                    data[node]['monitor'].insert(0, value)
                    data[node]['monitor'].pop()
                stable = stable and Common.is_stable(
                    data[node]['monitor'], float(threshold), int(percentile))
                BuiltIn().log("node = %s stable = %s" % (node, stable))
                BuiltIn().log(",".join(str(i) for i in data[node]['monitor']))

            count += 1
            time.sleep(interval)

        if count < max_len:
            BuiltIn().log("Stable checking normaly finished")
        else:
            BuiltIn().log("Stable chekcing forcely finsined")
Beispiel #5
0
 def start(self):
     try:
         self.session = netsnmp.SNMPSession(self.host, self.community)
     except SNMPError as e:
         raise e
Beispiel #6
0
#!/usr/bin/env python
import sys
import netsnmp

if __name__ == '__main__':
    ip = '127.0.0.1'
    snmp = netsnmp.SNMPSession(ip, 'RJKJ')
    if snmp.is_alive():
        snmp.close()
print 'test import netsnmp ok'