Example #1
0
 def detect(self):
  ret = {}
  from zdcp.SettingsContainer import SC
  from netsnmp import VarList, Varbind, Session
  try:
   # .1.3.6.1.2.1.1.1.0 : Device info
   # .1.3.6.1.2.1.1.5.0 : Device name
   devobjs = VarList(Varbind('.1.3.6.1.2.1.1.1.0'), Varbind('.1.3.6.1.2.1.1.5.0'))
   session = Session(Version = 2, DestHost = self._ip, Community = SC['snmp']['read_community'], UseNumeric = 1, Timeout = 100000, Retries = 2)
   session.get(devobjs)
   ret['result'] = "OK" if (session.ErrorInd == 0) else "NOT_OK"
  except Exception as err:
   ret['snmp'] = "Not able to do SNMP lookup (check snmp -> read_community): %s"%str(err)
  else:
   ret['info'] = {'model':'unknown', 'type':'generic','snmp':devobjs[1].val.lower() if devobjs[1].val else 'unknown'}
   if devobjs[0].val:
    infolist = devobjs[0].val.split()
    if infolist[0] == "Juniper":
     if infolist[1] == "Networks,":
      ret['info']['model'] = infolist[3].lower()
      for tp in [ 'ex', 'srx', 'qfx', 'mx', 'wlc' ]:
       if tp in ret['info']['model']:
        ret['info']['type'] = tp
        break
     else:
      subinfolist = infolist[1].split(",")
      ret['info']['model'] = subinfolist[2]
    elif infolist[0] == "VMware":
     ret['info']['model'] = "esxi"
     ret['info']['type']  = "esxi"
    elif infolist[0] == "Linux":
     ret['info']['model'] = 'debian' if "Debian" in devobjs[0].val else 'generic'
    else:
     ret['info']['model'] = " ".join(infolist[0:4])
  return ret
Example #2
0
 def interfaces(self):
     from sdcp.SettingsContainer import SC
     from netsnmp import VarList, Varbind, Session
     interfaces = {}
     try:
         objs = VarList(Varbind('.1.3.6.1.2.1.2.2.1.2'),
                        Varbind('.1.3.6.1.2.1.31.1.1.1.18'))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.walk(objs)
         for entry in objs:
             intf = interfaces.get(int(entry.iid), {
                 'name': "None",
                 'description': "None"
             })
             if entry.tag == '.1.3.6.1.2.1.2.2.1.2':
                 intf['name'] = entry.val
             if entry.tag == '.1.3.6.1.2.1.31.1.1.1.18':
                 intf[
                     'description'] = entry.val if entry.val != "" else "None"
             interfaces[int(entry.iid)] = intf
     except Exception as exception_error:
         self.log_msg("Generic : error traversing interfaces: " +
                      str(exception_error))
     return interfaces
Example #3
0
 def get_vm_state(self, aid):
  from netsnmp import VarList, Varbind, Session
  try:
   vmstateobj = VarList(Varbind(".1.3.6.1.4.1.6876.2.1.1.6." + str(aid)))
   session = Session(Version = 2, DestHost = self._ip, Community = SC['snmp']['read_community'], UseNumeric = 1, Timeout = 100000, Retries = 2)
   session.get(vmstateobj)
   return vmstateobj[0].val
  except:
   pass
  return "unknown"
Example #4
0
 def get_vm_id(self, aname):
  from netsnmp import VarList, Varbind, Session
  try:
   vmnameobjs = VarList(Varbind('.1.3.6.1.4.1.6876.2.1.1.2'))
   session = Session(Version = 2, DestHost = self._ip, Community = SC['snmp']['read_community'], UseNumeric = 1, Timeout = 100000, Retries = 2)
   session.walk(vmnameobjs)
   for result in vmnameobjs:
    if result.val == aname:
     return int(result.iid)
  except:
   pass
  return -1
Example #5
0
 def get_inventory(self):
     from netsnmp import VarList, Varbind, Session
     result = []
     try:
         outletobjs = VarList(Varbind('.1.3.6.1.4.1.10418.17.2.5.5.1.4'))
         stateobjs = VarList(Varbind('.1.3.6.1.4.1.10418.17.2.5.5.1.5'))
         slotobjs = VarList(Varbind('.1.3.6.1.4.1.10418.17.2.5.3.1.3'))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.walk(outletobjs)
         session.walk(stateobjs)
         session.walk(slotobjs)
         slotdict = dict(map(lambda var: (var.iid, var.val), slotobjs))
         for indx, outlet in enumerate(outletobjs, 0):
             result.append({
                 'slot':
                 outlet.tag[34:],
                 'unit':
                 outlet.iid,
                 'name':
                 outlet.val,
                 'state':
                 Device.get_outlet_state(stateobjs[indx].val),
                 'slotname':
                 slotdict.get(outlet.tag[34:], "unknown")
             })
     except Exception as exception_error:
         self.log_msg("Avocent : error loading conf " +
                      str(exception_error))
     return result
Example #6
0
    def get_switch_model(self, ip):
        """ Возвращает класс свитча """

        oid_system = 'iso.3.6.1.2.1.1.1.0'
        sess = Session(Version=self.version, DestHost=ip, Community=self.community)
        cl, = sess.get(VarList(Varbind(oid_system)))

        if not cl:
            return {
                'status' : Status.ERROR,
                'msg'    : 'Предположительно свитч лежит!'
            }

        pattern = compile('(?:D[GE]S|D-Link)')
        if 'Huawei' in cl:
            if 'S2300' in cl:
                return {
                    'status' : Status.SUCCESS,
                    'sw'     : S2300(self.swconf, ip)
                }
            elif 'CX200' in cl:
                return {
                    'status' : Status.SUCCESS,
                    'sw'     : CX200(self.swconf, ip)
                }
            elif 'S3328' in cl:
                return {
                    'status' : Status.SUCCESS,
                    'sw'     : S3328(self.swconf, ip)
                }
            else:
                print(cl)
                return {
                    'status' : Status.NOTFOUND
                }
        elif search(pattern, cl):
            if '3026' in cl:
                return {
                    'status' : Status.SUCCESS,
                    'sw'     : D3026(self.swconf, ip)
                }
            return {
                'status' : Status.SUCCESS,
                'sw'     : Dlink(self.swconf, ip)
            }
        print(cl)
        return {
            'status' : Status.NOTFOUND
        }
 def connect(self):
     self.session = Session(
         DestHost=self.host,
         Community=self.community,
         Version=self.version,
         UseNumeric=1,
     )
Example #8
0
 def connect(self):
     #resolve hostname
     try:
         ip = gethostbyname(self.host)
     except:
         logging.debug('Could not resolve', self.host, 'connection failed')
         self.session = None
         return None
     self.session = Session(
         DestHost=ip,
         Community=self.community,
         Version=self.version,
         UseNumeric=1,
         Timeout=self.timeout,
         Retries=self.retries,
     )
Example #9
0
def detect(aDict):
 """Function docstring for detect TBD. TODO -> make this a function of generic device instead !!! ZEB

 Args:
  - ip (required)

 Output:
 """
 from os import system
 if system("ping -c 1 -w 1 {} > /dev/null 2>&1".format(aDict['ip'])) != 0:
  return {'result':'NOT_OK', 'info':'Not pingable' }

 ret = {'result':'OK'}

 from netsnmp import VarList, Varbind, Session
 try:
  # .1.3.6.1.2.1.1.1.0 : Device info
  # .1.3.6.1.2.1.1.5.0 : Device name
  devobjs = VarList(Varbind('.1.3.6.1.2.1.1.1.0'), Varbind('.1.3.6.1.2.1.1.5.0'))
  session = Session(Version = 2, DestHost = aDict['ip'], Community = SC['snmp']['read_community'], UseNumeric = 1, Timeout = 100000, Retries = 2)
  session.get(devobjs)
 except Exception as err:
  ret['snmp'] = "Not able to do SNMP lookup (check snmp -> read_community): %s"%str(err) 

 ret['info'] = {'model':'unknown', 'type':'generic','snmp':devobjs[1].val.lower() if devobjs[1].val else 'unknown'}

 if devobjs[0].val:
  infolist = devobjs[0].val.split()
  if infolist[0] == "Juniper":
   if infolist[1] == "Networks,":
    ret['info']['model'] = infolist[3].lower()
    for tp in [ 'ex', 'srx', 'qfx', 'mx', 'wlc' ]:
     if tp in ret['info']['model']:
      ret['info']['type'] = tp
      break
   else:
    subinfolist = infolist[1].split(",")
    ret['info']['model'] = subinfolist[2]
  elif infolist[0] == "VMware":
   ret['info']['model'] = "esxi"
   ret['info']['type']  = "esxi"
  elif infolist[0] == "Linux":
   ret['info']['model'] = 'debian' if "Debian" in devobjs[0].val else 'generic'
  else:
   ret['info']['model'] = " ".join(infolist[0:4])

 return ret
Example #10
0
 def get_slot_names(self):
     from netsnmp import VarList, Varbind, Session
     slots = []
     try:
         slotobjs = VarList(Varbind('.1.3.6.1.4.1.10418.17.2.5.3.1.3'))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.walk(slotobjs)
         for slot in slotobjs:
             slots.append([slot.iid, slot.val])
     except Exception as exception_error:
         self.log_msg("Avocent : error loading pdu member names " +
                      str(exception_error))
     return slots
Example #11
0
 def set_name(self, slot, unit, name):
     from netsnmp import VarList, Varbind, Session
     try:
         name = name[:16]
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['write_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         setobj = VarList(
             Varbind("enterprises",
                     "10418.17.2.5.5.1.4.1.{}.{}".format(slot, unit), name,
                     "OPAQUE"))
         session.set(setobj)
         return "{0}.{1}:'{2}'".format(slot, unit, name)
     except Exception as exception_error:
         self.log_msg("Avocent : error setting name " +
                      str(exception_error))
         return "Error setting name '%s'" % (name)
Example #12
0
 def get_state(self, slot, unit):
     from netsnmp import VarList, Varbind, Session
     try:
         stateobj = VarList(
             Varbind(".1.3.6.1.4.1.10418.17.2.5.5.1.5.1.{}.{}".format(
                 slot, unit)))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.get(stateobj)
         return {
             'res': 'OK',
             'state': Device.get_outlet_state(stateobj[0].val)
         }
     except Exception as e:
         self.log_msg("Avocent : error getting state:" + str(e))
         return {'res': 'NOT_OK', 'info': str(e), 'state': 'unknown'}
Example #13
0
 def set_state(self, slot, unit, state):
     from netsnmp import VarList, Varbind, Session
     try:
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['write_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         setobj = VarList(
             Varbind("enterprises",
                     "10418.17.2.5.5.1.6.1.{}.{}".format(slot, unit),
                     Device.set_outlet_state(state), "INTEGER"))
         session.set(setobj)
         self.log_msg("Avocent : {0} set state to {1} on {2}.{3}".format(
             self._ip, state, slot, unit))
         return {'res': 'OK'}
     except Exception as exception_error:
         self.log_msg("Avocent : error setting state " +
                      str(exception_error))
         return {'res': 'NOT_OK', 'info': str(exception_error)}
Example #14
0
 def get_vm_list(self, aSort=None):
     # aSort = 'id' or 'name'
     from netsnmp import VarList, Varbind, Session
     statelist = []
     try:
         vmnameobjs = VarList(Varbind('.1.3.6.1.4.1.6876.2.1.1.2'))
         vmstateobjs = VarList(Varbind('.1.3.6.1.4.1.6876.2.1.1.6'))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.walk(vmnameobjs)
         session.walk(vmstateobjs)
         for indx, result in enumerate(vmnameobjs):
             statetuple = {
                 'id': result.iid,
                 'name': result.val,
                 'state': vmstateobjs[indx].val,
                 'state_id': Device.get_state_str(vmstateobjs[indx].val)
             }
             statelist.append(statetuple)
     except:
         pass
     if aSort:
         statelist.sort(key=lambda x: x[aSort])
     return statelist
class SNMPSession:
    def __init__(self, host, community, version=2):
        self.session = None
        self.host = host
        self.community = community
        self.version = version

    def connect(self):
        self.session = Session(
            DestHost=self.host,
            Community=self.community,
            Version=self.version,
            UseNumeric=1,
        )

    def walk(self, oid, stripoid=True):
        if not self.session:
            self.connect()

        vb = Varbind(oid)
        vl = VarList(vb)
        self.session.walk(vl)
        ret = {}
        for v in vl:
            if v.tag is None:
                continue
            full_oid = v.tag
            if v.iid or v.iid == 0:
                full_oid = v.tag + "." + v.iid
            if stripoid:
                full_oid = full_oid.replace(oid, '')
                full_oid = full_oid.replace(".", '')
            ret[full_oid] = v.val
        return ret

    def get(self, oid):
        if not self.session:
            self.connect()
        return self.session.get(oid)[0]
Example #16
0
 def get_inventory(self):
     from netsnmp import VarList, Varbind, Session
     from sdcp.SettingsContainer import SC
     result = []
     try:
         portobjs = VarList(Varbind('.1.3.6.1.4.1.25049.17.2.1.2'))
         session = Session(Version=2,
                           DestHost=self._ip,
                           Community=SC['snmp']['read_community'],
                           UseNumeric=1,
                           Timeout=100000,
                           Retries=2)
         session.walk(portobjs)
         for obj in portobjs:
             result.append({
                 'interface': obj.iid,
                 'name': obj.val,
                 'port': str(6000 + int(obj.iid))
             })
     except Exception as exception_error:
         self.log_msg("OpenGear : error loading conf " +
                      str(exception_error))
     return result
Example #17
0
    def switch_table(self):
        from socket import gethostbyaddr
        try:
            # Length of below is used to offset ip address (32) + 1 and mac base (33) + 1
            cssidobjs = VarList(Varbind(".1.3.6.1.4.1.14525.4.4.1.1.1.1.15"))
            cipobjs = VarList(Varbind(".1.3.6.1.4.1.14525.4.4.1.1.1.1.4"))

            from sdcp.SettingsContainer import SC
            session = Session(Version=2,
                              DestHost=self._ip,
                              Community=SC['snmp']['read_community'],
                              UseNumeric=1,
                              Timeout=100000,
                              Retries=2)
            session.walk(cssidobjs)
            session.walk(cipobjs)
        except:
            return

        ipdict = dict(map(lambda res: (res.tag[33:], res.val), cipobjs))
        ret = []
        for res in cssidobjs:
            macbase = res.tag[34:]
            mac = (macbase + "." + res.iid).split(".")
            mac = ":".join(map(lambda x: hex(int(x))[2:], mac))
            try:
                clientname = gethostbyaddr(ipdict[macbase])[0]
            except:
                clientname = "unknown"
            ret.append({
                'Name': clientname,
                'IP': ipdict.get(macbase),
                'MAC': mac,
                'SSID': res.val
            })
        return ret
Example #18
0
class SNMPSession:
    def __init__(self,
                 host,
                 community,
                 version=2,
                 timeout=2000000,
                 retries=0,
                 max_repetitions=49):
        self.session = None
        self.host = host
        self.community = community
        self.version = version
        self.timeout = timeout
        self.retries = retries
        self.max_rep = max_repetitions

    def connect(self):
        #resolve hostname
        try:
            ip = gethostbyname(self.host)
        except:
            logging.debug('Could not resolve', self.host, 'connection failed')
            self.session = None
            return None
        self.session = Session(
            DestHost=ip,
            Community=self.community,
            Version=self.version,
            UseNumeric=1,
            Timeout=self.timeout,
            Retries=self.retries,
        )

    def walk(self, oid, stripoid=True, expect_str=False):
        vb = Varbind(oid)
        vl = VarList(vb)
        self.session.walk(vl)
        ret = {}
        for v in vl:
            if v.tag is None:
                continue
            full_oid = v.tag
            (full_oid, val) = handle_vb(v, expect_str)
            if stripoid:
                full_oid = full_oid.replace(oid + ".", '')
            ret[full_oid] = val
        return ret

    def bulkwalk(self,
                 oid,
                 stripoid=True,
                 startidx=None,
                 endidx=None,
                 expect_str=False):
        ret = {}
        if oid[0] != ".":
            oid = "." + oid
        startindexpos = startidx
        runningtreename = oid
        stop = False

        while (runningtreename.startswith(oid) and stop is False):
            vrs = VarList(Varbind(runningtreename, startindexpos))
            result = self.session.getbulk(0, self.max_rep, vrs)
            if self.session.ErrorInd:
                logging.warn("walk failed on: {0} ({1})".format(
                    self.host, self.session.ErrorStr))
            key = None
            if not result:
                logging.warn("got no result: %s %s", self.host, oid)
                break
            """ Print output from running getbulk"""
            for i in vrs:
                if endidx and int(i.iid) > int(endidx):
                    stop = True
                    break
                if not i.tag.startswith(oid):
                    break
                (full_oid, val) = handle_vb(i, expect_str)
                key = full_oid.replace(oid + ".", "")
                if stripoid:
                    ret[key] = val
                else:
                    ret[full_oid] = val
            """ Set startindexpos for next getbulk """
            if not vrs[-1].iid or not key or stop:
                break
            startindexpos = vrs[-1].iid
            """ Refresh runningtreename from last result"""
            runningtreename = vrs[-1].tag

        return ret

    def get(self, oid):
        return self.session.get(oid)[0]