Ejemplo n.º 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
Ejemplo n.º 2
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"
Ejemplo n.º 3
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
Ejemplo n.º 4
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'}
Ejemplo n.º 5
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
        }
Ejemplo n.º 6
0
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]
Ejemplo n.º 7
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]