Example #1
0
    def update(self):
        try:
            # pass
            port = '4'
            index = '13'

            oid = netsnmp.Varbind('.1.3.6.1.4.1',
                                  '.2011.5.25.157.1.1.1.1.15.9', '2',
                                  'INTEGER')
            # print netsnmp.snmpset(oid,Version=1,DestHost='10.15.9.253',Community='private@it')
            print netsnmp.snmpget('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5',
                                  Version=1,
                                  DestHost='10.15.9.253',
                                  Community='private@it')
            print netsnmp.snmpgetnext(
                '.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5',
                Version=1,
                DestHost='10.15.9.253',
                Community='private@it')
            print netsnmp.snmpwalk('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15',
                                   Version=1,
                                   DestHost='10.15.9.253',
                                   Community='private@it')
        except Exception, err:
            print err
def getdetails(host, community):

  # HP ETHERNET MULTI-ENVIRONMENT,SN:XXXXXXXXXX,FN:XXXXXXX,SVCID:XXXXX,PID:HP LaserJet CM1415fn

  details = dict()

  # sysName.0
  details['name']    = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.5.0'), Version = 1, DestHost=host, Community=community)[0]

  # sysContact.0
  details['contact'] = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.4.0'), Version = 1, DestHost=host, Community=community)[0]

  # sysUpTimeInstance
  details['uptime'] = int(netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.3.0'), Version = 1, DestHost=host, Community=community)[0]) / 100

  # sysDescr.0
  res = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'), Version = 1, DestHost=host, Community=community)

  match = re.search(r'HP ETHERNET MULTI-ENVIRONMENT,SN:(.*),FN:(.*),SVCID:(.*),PID:(.*)', res[0])

  if match:

    details['sn']    = match.group(1)
    details['fn']    = match.group(2)
    details['svcid'] = match.group(3)
    details['pid']   = match.group(4)

    return details
def getconsumableslevels(host, community):

    consumables_number = len(
        netsnmp.snmpwalk(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1"),
                         Version=1,
                         DestHost=host,
                         Community=community))
    res = dict()

    for i in range(1, consumables_number + 1):

        res[i] = dict()

        res[i]['name'] = netsnmp.snmpget(
            netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1." + str(i)),
            Version=1,
            DestHost=host,
            Community=community)[0]
        res[i]['level'] = netsnmp.snmpget(
            netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.9.1." + str(i)),
            Version=1,
            DestHost=host,
            Community=community)[0]

    return res
Example #4
0
def generate(out, ip, switch):
  # Get Cisco model name (two tries)
  for i in xrange(2):
    var = netsnmp.Varbind('.1.3.6.1.2.1.47.1.1.1.1.13.1')
    model = netsnmp.snmpget(var, Version=2, DestHost=ip, Community='private')[0]

    if model == None:
      var = netsnmp.Varbind('.1.3.6.1.2.1.47.1.1.1.1.13.1001')
      model = netsnmp.snmpget(var, Version=2, DestHost=ip, Community='private')[0]
    
  if model == None:
    sw_reload(ip)
    error("Could not get model for switch" , ip)
    return

  if not model in config.models:
    sw_reload(ip)
    error("Template for model " + model_id + " not found")
    return

  # Throws exception if something bad happens
  try:
    txt = config.generate(switch, model)
    out.write("! Config for " + switch + "\n")
    out.write(txt)
  except:
    sw_reload(ip)
    error("Exception in generation for %s :" % switch, traceback.format_exc())
    out.close()
    return None

  return out
def notify(ip_addr, cable_deltas):
    import email.mime.text
    from smtplib import SMTP
    import socket

    # make message
    nameoid = netsnmp.Varbind(".1.3.6.1.2.1.1.6.0")
    namesw = netsnmp.snmpget(
        nameoid, Version=2, DestHost=ip_addr, Community=COMMUNITY)
    msg_items = [u'Подозрения на вырез кабеля: %s по адресу %s\n\n' %
                 (ip_addr, namesw), ]
    for port, delta in cable_deltas.items():
        dloid = netsnmp.Varbind(".1.3.6.1.4.1.171.12.58.1.1.1.8.%s" % port)
        tekdlina = netsnmp.snmpget(
            dloid, Version=2, DestHost=ip_addr, Community=COMMUNITY)
        msg_items.append(u'порт %d: ' % port +
                         u'вырезанная длина %d текущая длина %s\n\n' % (delta, tekdlina[0]))

     # send email
    msg = email.mime.text.MIMEText(u''.join(msg_items), 'plain', 'utf-8')
    msg['Subject'] = u'Подозрения на вырез кабеля'
    msg['From'] = 'monitoring'
    msg['To'] = ', '.join(NOTIFICATION['email'])

    smtp = SMTP()
    smtp.connect('mail.ru', 25)
    smtp.login('monitoring', 'password')
    smtp.sendmail('monitoring@ru', NOTIFICATION['email'], msg.as_string())
    smtp.quit()
Example #6
0
def update_rrd(Host, eth_in_oid, eth_out_oid, rrd_path, auth):
    eth_in_trffic = netsnmp.snmpget(eth_in_oid, Version=2, DestHost=Host, Community=auth)[0]
    eth_out_trffic = netsnmp.snmpget(eth_out_oid, Version=2, DestHost=Host, Community=auth)[0]
    ret = rrd_update(rrd_path, 'N:%s:%s' %(eth_in_trffic, eth_out_trffic))
    if not ret:
        print rrdtool.error()
    print "update %s  N:%s:%s" %(rrd_path, eth_in_trffic, eth_out_trffic)
def check_neighbor_status_v4(host,community):
    peers_v4   = {}
    asns_v4    = {}
    reasons_v4 = {}
  
    # Walk all peers from BGP-MIB
    oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4'))
    res_v4  = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community)
  
    # Due to SNMP deamon lagg in the router, when switching communities from one to the other,
    # sometimes we fail to get snmp.
    # If we wait 5 sec and try again it should work just fine
    if not res_v4:
        time.sleep(5)
        oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4'))
        res_v4  = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community)
        
    for oid_v4 in oids_v4:
        ipv4           = oid_v4.tag.replace("enterprises.9.9.187.1.2.5.1.3.1.4.", "")
        peers_v4[ipv4] = get_state(oid_v4.val)
    
        # Get RemoteAs from BGP-MIB
        asoid         = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.11.1.4.'+ipv4)
        asn           = netsnmp.snmpget( asoid, Version = 2, DestHost = host, Community = community )
        asns_v4[ipv4] = asn[0]
    
        # Get lastErrorTxt from BGP-MIB
        reasonoid        = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.28.1.4.'+ipv4)
        reason           = netsnmp.snmpget( reasonoid, Version = 2, DestHost = host, Community = community )
        reasons_v4[ipv4] = reason[0]
        
    return (peers_v4,asns_v4,reasons_v4)
Example #8
0
def get_ring_status(remote_ip, community):
    ring_status_oid = netsnmp.Varbind('.1.3.6.1.4.1.9.9.500.1.1.3.0')
    logging.debug('Getting stack ring redundancy status -- ')
    netsnmp.snmpget(ring_status_oid, DestHost=remote_ip, Version=1, Community=community)
    if not ring_status_oid:
        plugin_exit(CRITICAL, 'Unable to retrieve SNMP ring status')
    logging.debug('Ring status: {0}'.format(ring_status_oid.print_str()))
    stack_ring_status = ring_status_oid.val
    return stack_ring_status
Example #9
0
    def collect(self):
        for obj in self.conf['items']:
            oid = netsnmp.Varbind(obj['value'])
            netsnmp.snmpget(oid,
                            DestHost=self.conf['hostname'],
                            Version=self.conf['snmp_version'],
                            Community=self.conf['snmp_community'],
                            UseNumeric=True)

            self.data[self.escape(obj['label'])] = oid.val
Example #10
0
def get_cisco_inet_traffic():
    """Returns (rcvd, sent).  Note that rcvd == inbound."""
    rcvd = netsnmp.snmpget('.1.3.6.1.2.1.2.2.1.10.49',
                           Version = 1,
                           Community = 'public',
                           DestHost = cisco_hostname)[0]
    sent = netsnmp.snmpget('.1.3.6.1.2.1.2.2.1.16.49',
                           Version = 1,
                           Community = 'public',
                           DestHost = cisco_hostname)[0]
    return int(rcvd), int(sent)
Example #11
0
def getlevel(cnt,ipn):
		cur_capacity = netsnmp.Varbind('.1.3.6.1.2.1.43.11.1.1.9.1.%d' % cnt)
		cur_level = netsnmp.snmpget(cur_capacity, Version=1, DestHost=ipn, Community='public', Timeout=100000, Retries=1)
		color_bind = netsnmp.Varbind('.1.3.6.1.2.1.43.11.1.1.6.1.%d' % cnt)
		color_name = netsnmp.snmpget(color_bind, Version=1, DestHost=ipn, Community='public', Timeout=100000, Retries=1)
		max_capacity = netsnmp.Varbind('.1.3.6.1.2.1.43.11.1.1.8.1.%d' % cnt)
		max_level = netsnmp.snmpget(max_capacity, Version=1, DestHost=ipn, Community='public', Timeout=100000, Retries=1)
		if max_level < 0:
			max_level == 0
		levels = color_name + cur_level + max_level
		return levels
Example #12
0
def get_cisco_inet_traffic():
    """Returns (rcvd, sent).  Note that rcvd == inbound."""
    rcvd = netsnmp.snmpget('.1.3.6.1.2.1.2.2.1.10.49',
                           Version=1,
                           Community='public',
                           DestHost=cisco_hostname)[0]
    sent = netsnmp.snmpget('.1.3.6.1.2.1.2.2.1.16.49',
                           Version=1,
                           Community='public',
                           DestHost=cisco_hostname)[0]
    return int(rcvd), int(sent)
def check_neighbor_status_v6(host,community):
    peers_v6  = {}
    asns_v6   = {}
    reasons_v6= {}
  
    # Walk all peers from BGP-MIB
    oids_v6 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.2.16'))
    res_v6  = netsnmp.snmpwalk( oids_v6, Version = 2, DestHost = host, Community = community )
  
    for oid_v6 in oids_v6:
        ipv6 = oid_v6.tag.split('.')
        oid  = oid_v6.tag
    
        # Convert into hexadecimal, each variable 16 bytes long
        a = ipv6_converter(ipv6[11]) +ipv6_converter(ipv6[12])
        b = ipv6_converter(ipv6[13]) +ipv6_converter(ipv6[14])
        c = ipv6_converter(ipv6[15]) +ipv6_converter(ipv6[16])
        d = ipv6_converter(ipv6[17]) +ipv6_converter(ipv6[18])
        e = ipv6_converter(ipv6[19]) +ipv6_converter(ipv6[20])
        f = ipv6_converter(ipv6[21]) +ipv6_converter(ipv6[22])
        g = ipv6_converter(ipv6[23]) +ipv6_converter(ipv6[24])
        h = ipv6_converter(ipv6[25]) +ipv6_converter(ipv6[26])
    
        # Remove leading zeroes
        a = a.lstrip("0")
        b = b.lstrip("0")
        c = c.lstrip("0")
        d = d.lstrip("0")
        e = e.lstrip("0")
        f = f.lstrip("0")
        g = g.lstrip("0")
        h = h.lstrip("0")
    
        # Contstruct properly formatted IPv6 address
        ipv6 = a +':' +b +':' +c +':' +d +':' +e +':' +f +':' +g
        ipv6 = ipv6.rstrip(":")
        ipv6 = ipv6 +'::' +h
    
        peers_v6[ipv6] = get_state(oid_v6.val)
    
        # Get RemoteAs from BGP-MIB
        oid           = oid.replace("enterprises.9.9.187.1.2.5.1.3.2.16.", "enterprises.9.9.187.1.2.5.1.11.2.16.")
        asoid         = netsnmp.Varbind(oid)
        asn           = netsnmp.snmpget( asoid, Version = 2, DestHost = host, Community = community )
        asns_v6[ipv6] = asn[0]
    
        # Get lastErrorTxt from BGP-MIB
        oid              = oid.replace("enterprises.9.9.187.1.2.5.1.11.2.16.", "enterprises.9.9.187.1.2.5.1.28.2.16.")
        reasonoid        = netsnmp.Varbind(oid)
        reason           = netsnmp.snmpget( reasonoid, Version = 2, DestHost = host, Community = community )
        reasons_v6[ipv6] = reason[0]
        
    return (peers_v6,asns_v6,reasons_v6)
def getdetails(host, community):

  # HP ETHERNET MULTI-ENVIRONMENT,SN:XXXXXXXXXX,FN:XXXXXXX,SVCID:XXXXX,PID:HP LaserJet CM1415fn
  # Xerox WorkCentre 6505N; Net 95.45,ESS 201104251224,IOT 02.00.02,Boot 201009241127
  # Xerox WorkCentre 7845 v1; SS 072.040.004.09100, NC 072.044.09100, UI 072.044.09100, ME 090.079.000, CC 072.044.09100, DF 007.019.000, FI 032.054.000, FA 003.011.009, CCOS 072.004.09100, NCOS 072.004.09100, SC 008.088.000, SU 010.116.00294
  # Lexmark CX510de version NH63.GM.N638 kernel 3.0.0 All-N-1

  details = dict()

  # sysName.0
  details['name']    = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.5.0'), Version = 1, DestHost=host, Community=community)[0]

  # sysContact.0
  details['contact'] = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.4.0'), Version = 1, DestHost=host, Community=community)[0]

  # sysUpTimeInstance
  details['uptime'] = int(netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.3.0'), Version = 1, DestHost=host, Community=community)[0]) / 100

  # sysDescr.0
  res = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'), Version = 1, DestHost=host, Community=community)

  # Default details values (unknown)
  details['sn']    = 'unknown'
  details['fn']    = details['sn']
  details['svcid'] = details['sn']
  details['pid']   = details['sn']

  # Case 1: HP printer
  match = re.search(r'HP ETHERNET MULTI-ENVIRONMENT,SN:(.*),FN:(.*),SVCID:(.*),PID:(.*)', res[0])

  if match:

    details['sn']    = match.group(1)
    details['fn']    = match.group(2)
    details['svcid'] = match.group(3)
    details['pid']   = match.group(4)

  # Case 2: Xerox printer
  match = re.search(r'Xerox (.*);', res[0])

  if match:

    details['pid']    = 'Xerox ' + match.group(1)

  # Case 3: Xerox printer
  match = re.search(r'Lexmark (.*) version (.*) kernel (.*)', res[0])

  if match:

    details['pid']    = 'Lexmark ' + match.group(1)

  return details
def getconsumableslevels(host, community):

  consumables_number = len(netsnmp.snmpwalk(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1"), Version = 1, DestHost=host, Community=community))
  res = dict()

  for i in range(1, consumables_number + 1):

    res[i] = dict()

    res[i]['name'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1." + str(i)), Version = 1, DestHost=host, Community=community)[0]
    res[i]['level'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.9.1." + str(i)), Version = 1, DestHost=host, Community=community)[0]

  return res
Example #16
0
def update_rrd(Host, eth_in_oid, eth_out_oid, rrd_path, auth):
    eth_in_trffic = netsnmp.snmpget(eth_in_oid,
                                    Version=2,
                                    DestHost=Host,
                                    Community=auth)[0]
    eth_out_trffic = netsnmp.snmpget(eth_out_oid,
                                     Version=2,
                                     DestHost=Host,
                                     Community=auth)[0]
    ret = rrd_update(rrd_path, 'N:%s:%s' % (eth_in_trffic, eth_out_trffic))
    if not ret:
        print rrdtool.error()
    print "update %s  N:%s:%s" % (rrd_path, eth_in_trffic, eth_out_trffic)
def getcartridgelevels(host, community):

  cartridge_number = 5

  res = dict()

  for i in range(1, cartridge_number):

    res[i] = dict()

    res[i]['name'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1." + str(i)), Version = 1, DestHost=host, Community=community)[0]
    res[i]['level'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.9.1." + str(i)), Version = 1, DestHost=host, Community=community)[0]

  return res
def Disk_Controller():
    disk_controller_name_list = []
    disk_controller_status_list = []
    problem_disk_controller_list = []
    disk_controller_status_Dict = {}

    disk_controller_name_oid = str(
        ".1.3.6.1.4.1.674.10892.5.5.1.20.130.1.1.2.")
    for i in range(1, 4):
        disk_controller_name_suboid = disk_controller_name_oid + str(i)
        disk_controller_name = netsnmp.snmpget(
            netsnmp.Varbind(disk_controller_name_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(disk_controller_name[0]) != str("None"):
            disk_controller_name_list.append(disk_controller_name[0])
        else:
            break

    disk_controller_status_oid = str(
        ".1.3.6.1.4.1.674.10892.5.5.1.20.130.1.1.38.")
    for i in range(1, 4):
        disk_controller_status_suboid = disk_controller_status_oid + str(i)
        disk_controller_status = netsnmp.snmpget(
            netsnmp.Varbind(disk_controller_status_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(disk_controller_status[0]) != str("None"):
            disk_controller_status_list.append(disk_controller_status[0])
        else:
            break

    disk_controller_status_Dict = dict(
        zip(disk_controller_name_list, disk_controller_status_list))

    for (k, i) in disk_controller_status_Dict.items():
        if i != str(3):
            problem_disk_controller_list.append(k)

    if len(problem_disk_controller_list) == 0:
        for i in disk_controller_name_list:
            print i,
        print "is OK,",

    else:
        for i in problem_disk_controller_list:
            print i,
        print "is problem,",
Example #19
0
    def is_listening():
        if p.poll() is not None:
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        num_sockets = 0
        try:
            for e in os.listdir("/proc/%d/fd" % p.pid):
                try:
                    if os.readlink("/proc/%d/fd/%s" % (p.pid, e)).startswith("socket:"):
                        num_sockets += 1
                except OSError:
                    pass
        except OSError:
            if p.poll() is None:
                raise
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        if num_sockets < 2:
            return False

        # Correct module is only available in the site
        import netsnmp  # type: ignore[import] # pylint: disable=import-error,import-outside-toplevel
        var = netsnmp.Varbind("sysDescr.0")
        result = netsnmp.snmpget(var, Version=2, DestHost="127.0.0.1:1337", Community="public")
        if result is None or result[0] is None:
            return False
        return True
Example #20
0
def snmp_get(host, credential, object_type, **kwargs):
    """Impelmentation of snmp get functionality

    :param object_type: mib object
    :param host: switch ip
    :param credential: the dict of credential to access switch
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'version' not in credential or 'community' not in credential:
        logging.error('[uitls][snmp_get] missing keywords in %s for %s',
                      credential, host)
        return None

    version = None
    if credential['version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['version']]

    varbind = netsnmp.Varbind(object_type)
    res = netsnmp.snmpget(varbind,
                          DestHost=host,
                          Version=version,
                          Community=credential['community'],
                          **kwargs)
    if res and res[0]:
        return res[0]

    logging.info('no result found for %s %s', host, credential)
    return None
Example #21
0
    def target_function(self, running, data):
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...')

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable, Version = 1, DestHost = address, Community=string)

                if res[0] != None:
                    running.clear()
                    print_success("{}: Valid community string found!".format(name), string)
                    self.strings.append(tuple([string]))
                else:
		    pass
                    # print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
Example #22
0
def snmp_get(host, credential, object_type):
    """Impelmentation of snmp get functionality

    :param object_type: mib object
    :param host: switch ip
    :param credential: the dict of credential to access switch
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'Version' not in credential or 'Community' not in credential:
        logging.error('[uitls][snmp_get] missing keywords in %s for %s',
                      credential, host)
        return None

    if credential['Version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['Version']]
        credential['Version'] = version

    varbind = netsnmp.Varbind(object_type)
    res = netsnmp.snmpget(varbind, DestHost=host, **credential)
    if not res:
        logging.error('no result found for %s %s', host, credential)
        return None

    return res[0]
Example #23
0
    def target_function(self, running, data):
        module_verbosity = boolify(self.verbosity)
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...', verbose=module_verbosity)

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable,
                                      Version=1,
                                      DestHost=address,
                                      Community=string)

                if res[0] is not None:
                    running.clear()
                    print_success(
                        "Target: {}:{} {}: Valid community string found - String: '{}'"
                        .format(self.target, self.port, name, string),
                        verbose=module_verbosity)
                    self.strings.append((self.target, self.port, string))
                else:
                    print_error(
                        "Target: {}:{} {}: Invalid community string - String: '{}'"
                        .format(self.target, self.port, name, string),
                        verbose=module_verbosity)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.', verbose=module_verbosity)
Example #24
0
    def _snmp_discover_personality(self):
        '''Loads netsnmp mod and attempts to discover the host's personality
        via snmp by querying sysDescr'''
        varbind = netsnmp.snmpget(
            netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'),
            DestHost=self.hostname,
            Version=self.snmp_version,
            Community=self.snmp_community,
        )

        if varbind[0] is None:
            raise Error('%s: SNMP query failed' % self.hostname)

        sys_descr = varbind[0]

        for personality in PERSONALITIES:
            # skip generic personality
            if personality == 'generic':
                continue

            if re.search(PERSONALITIES[personality]['sys_descr'],
                         sys_descr,
                         flags=re.I):
                self.personality = personality
                break
        else:
            raise Error('%s: Unable to determine personality of "%s"' %
                        (self.hostname, sys_descr))
Example #25
0
	def snmp_get(self,iod):
		var=netsnmp.Varbind(iod)
		result = netsnmp.snmpget(var,
			Version = self.Version,
			DestHost = self.DestHost,
			Community = self.Community)
		return result
Example #26
0
    def __SNMPGET_netsnmp(self, oid, exitonerror=True):
        if not self.__prepared_snmp:
            self.prepare_snmp()

        if oid in self.__SNMP_Cache:
            self.verbose(2,
                         "%40s -> (CACHED) %s" % (oid, self.__SNMP_Cache[oid]))
            return self.__SNMP_Cache[oid]

        result = netsnmp.snmpget(oid,
                                 Version=int(self.options.snmpversion),
                                 DestHost=self.options.host,
                                 Community=self.options.snmpauth)[0]

        if not result:
            if exitonerror:
                self.back2nagios(
                    3, 'Timeout or no answer from "%s" looking for "%s"' %
                    (self.options.host, oid))
            else:
                return None

        self.__SNMP_Cache[oid] = result

        self.verbose(2, "%40s -> %s" % (oid, result))
        return result
Example #27
0
    def GetPower(self, unit, outlet):
        """
         @brief: This function returns the state of the specified outlet.

         @param outlet: The ID-number of the outlet for which the state will be returned.
      """

        if unit == "nasmyth": dest_host = pdu_config.DestHost_nasmyth
        elif unit == "container": dest_host = pdu_config.DestHost_container
        elif unit == "side_ports": dest_host = pdu_config.DestHost_side_ports
        elif unit == "nasmyth_2": dest_host = pdu_config.DestHost_nasmyth_2
        else: print "Error, wrong unit provided!"

        clock = song_timeclass.TimeClass()

        OID = ".1.3.6.1.4.1.318.1.1.4.4.2.1.3.%i" % int(outlet)

        powerstatus = ""
        try:
            powerstatus = netsnmp.snmpget(OID,
                                          Version=1,
                                          DestHost=dest_host,
                                          Community=pdu_config.Community)
        except Exception, e:
            sys.exit("ERROR, connection to PDU could not be made!")
Example #28
0
    def target_function(self, running, data):
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...')

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable,
                                      Version=1,
                                      DestHost=address,
                                      Community=string)

                if res[0] != None:
                    running.clear()
                    print_success(
                        "{}: Valid community string found!".format(name),
                        string)
                    self.strings.append(tuple([string]))
                else:
                    pass
                # print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
Example #29
0
    def is_listening():
        if p.poll() is not None:
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        num_sockets = 0
        try:
            for e in os.listdir("/proc/%d/fd" % p.pid):
                try:
                    if os.readlink("/proc/%d/fd/%s" % (p.pid, e)).startswith("socket:"):
                        num_sockets += 1
                except OSError:
                    pass
        except OSError:
            if p.poll() is None:
                raise
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        if num_sockets < 2:
            return False

        import netsnmp
        var = netsnmp.Varbind("sysDescr.0")
        result = netsnmp.snmpget(var, Version=2, DestHost="127.0.0.1:1337", Community="public")
        if result is None or result[0] is None:
            return False
        return True
Example #30
0
    def GetInfo(self, unit):
        """
         @brief: This function will return some info about the APC-PDU device. 

         @todo: This function could be filled with possibilities. 
      """

        if unit == "nasmyth":
            dest_host = pdu_config.DestHost_nasmyth
            pdu_names = pdu_config.names_nasmyth
        elif unit == "container":
            dest_host = pdu_config.DestHost_container
            pdu_names = pdu_config.names_container
        elif unit == "side_ports":
            dest_host = pdu_config.DestHost_side_ports
            pdu_names = pdu_config.names_side_ports
        elif unit == "nasmyth_2":
            dest_host = pdu_config.DestHost_nasmyth_2
            pdu_names = pdu_config.names_nasmyth_2
        else:
            print "Error, wrong unit provided!"

        clock = song_timeclass.TimeClass()
        OID = ".1.3.6.1.4.1.318.1.1.4.5.1.0"  # Returns the total number of outlets (24 with this PDU)

        powerstatus = ""
        try:
            powerstatus = netsnmp.snmpget(OID,
                                          Version=1,
                                          DestHost=dest_host,
                                          Community=pdu_config.Community)
        except Exception, e:
            sys.exit("ERROR, connection to PDU could not be made!")
    def target_function(self, running, data):
        module_verbosity = boolify(self.verbosity)
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...', verbose=module_verbosity)

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable, Version=1, DestHost=address, Community=string)

                if res[0] is not None:
                    running.clear()
                    print_success("Target: {}:{} {}: Valid community string found - String: '{}'".format(self.target, self.port, name, string), verbose=module_verbosity)
                    self.strings.append((self.target, self.port, string))
                else:
                    print_error("Target: {}:{} {}: Invalid community string - String: '{}'".format(self.target, self.port, name, string), verbose=module_verbosity)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.', verbose=module_verbosity)
Example #32
0
    def _snmp_discover_personality(self):
        '''Loads netsnmp mod and attempts to discover the host's personality
        via snmp by querying sysDescr'''
        varbind = netsnmp.snmpget(
            netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'),
            DestHost=self.hostname,
            Version=self.snmp_version,
            Community=self.snmp_community,
        )

        if varbind[0] is None:
            raise Error('%s: SNMP query failed' % self.hostname)

        sys_descr = varbind[0]

        for personality in PERSONALITIES:
            # skip generic personality
            if personality == 'generic':
                continue

            if re.search(
                    PERSONALITIES[personality]['sys_descr'], sys_descr,
                    flags=re.I
            ):
                self.personality = personality
                break
        else:
            raise Error(
                '%s: Unable to determine personality of "%s"' % (
                    self.hostname, sys_descr))
Example #33
0
def snmp_get(host, credential, object_type):
    """ Impelmentation of snmp get functionality

        param str  object_type : mib object
        param str  host        : switch ip
        param dict credential  : credential to access switch
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'Version' not in credential or 'Community' not in credential:
        logging.error('[uitls][snmp_get] missing keywords in %s for %s',
                      credential, host)
        return None

    if credential['Version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['Version']]
        credential['Version'] = version

    varbind = netsnmp.Varbind(object_type)
    res = netsnmp.snmpget(varbind, DestHost=host, **credential)
    if not res:
        logging.error('no result found for %s %s', host, credential)
        return None

    return res[0]
 def get_originators_nexthop(self):
     host = self.smp_ip
     mibr = netsnmp.Varbind('iso.3.6.1.4.1.32.1.2')
     orig = netsnmp.snmpget(mibr, Version=2, DestHost=host,
            Community='public', Timeout=50000, Retries=3)
     on = str(orig[0]).split()
     return on[::2], on[1::2]
Example #35
0
 def testsnmpgetcpu(self):
     '''snmp get cpu'''
     snmpvar = netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.1.23.0')
     res, = netsnmp.snmpget(snmpvar,
                            Version=self.snmpver,
                            DestHost=self.ipstr,
                            Community=self.community)
     self.assertTrue(str(res).isdigit())
Example #36
0
 def testsnmpget(self):
     '''snmp get oids'''
     snmpvar = netsnmp.Varbind('.1.3.6.1.2.1.1.1.0')
     res, = netsnmp.snmpget(snmpvar,
                            Version=self.snmpver,
                            DestHost=self.ipstr,
                            Community=self.community)
     self.assertIsNotNone(res)
Example #37
0
def snmp(oid, host, timeout=1):
    """Perform an SNMP lookup of an OID on a host, return the result."""
    debug_print("Quering SNMP agent on %s for OID '%s'." % (host, oid))
    var = netsnmp.Varbind(oid)
    result = netsnmp.snmpget(var, Version=2, DestHost=host, Community="public",
                             Timeout=(timeout * 1000000), Retries=0)
    debug_print("SNMP lookup returned result '%s'." % (result[0]))
    return result[0]
Example #38
0
 def get(self, oid):
     var = netsnmp.Varbind(oid)
     ret = netsnmp.snmpget(var,
                           Version=self.version,
                           Community=self.community,
                           UseNumeric=self.useNumeric,
                           DestHost=self.destination)
     return ret[0]
def Battery_Status():

    battery_location_oid = str(".1.3.6.1.4.1.674.10892.5.4.600.50.1.7.1.")
    battery_status_oid = str(".1.3.6.1.4.1.674.10892.5.4.600.50.1.5.1.")
    battery_location_list = []
    battery_status_list = []
    battery_problem_list = []
    battery_status_dict = {}

    for i in range(1, 8):
        battery_location_suboid = battery_location_oid + str(i)
        battery_location = netsnmp.snmpget(
            netsnmp.Varbind(battery_location_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(battery_location[0]) != str("None"):
            battery_location_list.append(battery_location[0])
        else:
            break

    for i in range(1, 8):
        battery_status_suboid = battery_status_oid + str(i)
        battery_status = netsnmp.snmpget(
            netsnmp.Varbind(battery_status_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(battery_status[0]) != str("None"):
            battery_status_list.append(str(battery_status[0]))
        else:
            break

    battery_status_dict = dict(zip(battery_location_list, battery_status_list))

    for (k, i) in battery_status_dict.items():
        if i[0] != str(3):
            battery_problem_list.append(k)

    if len(battery_problem_list) == 0:
        print "Battery is OK,",

    else:
        for i in battery_problem_list:
            print i,
        print "is problem,",
Example #40
0
   def processOID(self, oid):
      process = netsnmp.Varbind(oid)
      result  = netsnmp.snmpget(oid,
                                Version   = self.version,
                                DestHost  = self.host,
                                Community = self.user)

      return result
def snmpGet(host):
    #session = netsnmp.Session(Version=2, DestHost=host, Community=snmp_community)
    args = {"Version": 2, "DestHost": host, "Community": snmp_community}
    try:
        a_file = open(workingDirectory + "/" + host + ".pkl", "rb")
        lastSample = pickle.load(a_file)
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
        print "Warning! No last sample detected"
        lastSample = None

    newSample = dict()
    for idx in netsnmp.snmpwalk(netsnmp.Varbind("IF-MIB::ifIndex"), **args):
        ifname, oper, cin, cout, ifspeed = netsnmp.snmpget(
            netsnmp.Varbind("IF-MIB::ifName", idx),
            netsnmp.Varbind("IF-MIB::ifOperStatus", idx),
            netsnmp.Varbind("IF-MIB::ifHCInOctets", idx),
            netsnmp.Varbind("IF-MIB::ifHCOutOctets", idx),
            netsnmp.Varbind("IF-MIB::ifSpeed", idx), **args)
        assert (ifname is not None and cin is not None and cout is not None)

        #Skip internal interfaces
        if ifname == "Internal-Data0/1" or ifname == "diagnostic" or ifname == "nlp_int_tap" or ifname == "ccl_ha_nlp_int_tap" or ifname == "ha_ctl_nlp_int_tap" or ifname == "failover":
            continue

        # Only look at interfaces that are up
        if oper != "1":
            continue

        newSample[ifname] = {'cin': cin, 'cout': cout, 'ts': time.time()}

        if (lastSample is not None):
            # Formula: https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/8141-calculate-bandwidth-snmp.html
            deltaSeconds = int(newSample[ifname]['ts']) - int(
                lastSample[ifname]['ts'])
            deltaIn = int(newSample[ifname]['cin']) - int(
                lastSample[ifname]['cin'])
            deltaOut = int(newSample[ifname]['cout']) - int(
                lastSample[ifname]['cout'])
            utilizationIn = (float(deltaIn) * 8) / (
                float(deltaSeconds) * 1024 * 1024)  # Mbps
            utilizationOut = (float(deltaOut) * 8) / (
                float(deltaSeconds) * 1024 * 1024)  #Mbps

            #print("{} utz in: {} utz out: {}".format( ifname, utilizationIn, utilizationOut))

            fp = open(output_path + host + "-interfaces.csv", "a+")
            now = datetime.datetime.now()
            log = "{},{},{},{}".format(now, ifname, utilizationIn,
                                       utilizationOut)

            fp.write(log + '\n')
            fp.close()
        else:
            print("Warning! No last sample detected - skipping")
    a_file = open(workingDirectory + "/" + host + ".pkl", "wb")
    pickle.dump(newSample, a_file)
    a_file.close()
def PhyDisk_Status():
    phydisk_name_oid = str(".1.3.6.1.4.1.674.10892.5.5.1.20.130.4.1.55.")
    phydisk_status_oid = str(".1.3.6.1.4.1.674.10892.5.5.1.20.130.4.1.24.")
    phydisk_problem_list = []
    phydisk_name_list = []
    phydisk_status_list = []
    phydisk_status_dict = {}

    for i in range(1, 24):
        phydisk_name_suboid = phydisk_name_oid + str(i)
        phydisk_name = netsnmp.snmpget(netsnmp.Varbind(phydisk_name_suboid),
                                       Version=2,
                                       DestHost=(hosts),
                                       Community=(communitys))
        if str(phydisk_name[0]) != str("None"):
            phydisk_name_list.append(phydisk_name[0])
        else:
            break

    for i in range(1, 24):
        phydisk_status_suboid = phydisk_status_oid + str(i)
        phydisk_status = netsnmp.snmpget(
            netsnmp.Varbind(phydisk_status_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(phydisk_status[0]) != str("None"):
            phydisk_status_list.append(phydisk_status[0])
        else:
            break

    phydisk_status_dict = dict(zip(phydisk_name_list, phydisk_status_list))

    for (k, i) in phydisk_status_dict.items():
        if i[0] != str(3):
            phydisk_problem_list.append(k)

    if len(phydisk_problem_list) == 0:
        print "Physical Disk number %d" % int(
            len(phydisk_name_list)) + " is OK,",
    else:
        WarningNum = WarningNum + 1
        for i in phydisk_problem_list:
            print i,
        print "is Problem,",
Example #43
0
 def testsnmpgetpensentsystempower(self):
     '''snmp get pensentsystempower'''
     snmpvar = netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.1.13.0')
     res, = netsnmp.snmpget(snmpvar,
                            Version=self.snmpver,
                            DestHost=self.ipstr,
                            Community=self.community)
     print res
     self.assertTrue(str(res).isdigit())
def realizarBusca(propriedade, host):
    resultadoSys = netsnmp.snmpget(
        propriedade,
        Version = 2,
        DestHost = host,
        Community = "public"
    )

    return resultadoSys
Example #45
0
 def get(self, oid):
     var = netsnmp.Varbind(oid)
     ret = netsnmp.snmpget(
         var,
         Version=self.version,
         Community=self.community,
         UseNumeric=self.useNumeric,
         DestHost=self.destination)
     return ret[0]
Example #46
0
    def get(self, oid):
        """ Ejecuta el equivalente a un 'snmpget' con los parametros establecidos """

        try:
            result = netsnmp.snmpget(oid, Version=self.version, DestHost=self.desthost,
                                     SecName=self.username, Community=self.community, Timeout=self.timeout)
            return result
        except Exception as e:
            print type(e)
Example #47
0
    def get_snmp_metric(self, bucket, host, version, oid, community):
      logger.debug("Sending oid request to snmp : %s" % oid)
      try:
          snmp_oid = netsnmp.Varbind(oid)
          metric = netsnmp.snmpget(snmp_oid, Version = version, DestHost = host, Community = community)[0]
      except:
          logger.error(sys.exc_info())
          metric = 0

      return metric
Example #48
0
def getdetails(host, community):

    # HP ETHERNET MULTI-ENVIRONMENT,SN:XXXXXXXXXX,FN:XXXXXXX,SVCID:XXXXX,PID:HP LaserJet CM1415fn

    details = dict()

    # sysName.0
    details['name'] = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.5.0'),
                                      Version=1,
                                      DestHost=host,
                                      Community=community)[0]

    # sysContact.0
    details['contact'] = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.4.0'),
                                         Version=1,
                                         DestHost=host,
                                         Community=community)[0]

    # sysUpTimeInstance
    details['uptime'] = int(
        netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.3.0'),
                        Version=1,
                        DestHost=host,
                        Community=community)[0]) / 100

    # sysDescr.0
    res = netsnmp.snmpget(netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'),
                          Version=1,
                          DestHost=host,
                          Community=community)

    match = re.search(
        r'HP ETHERNET MULTI-ENVIRONMENT,SN:(.*),FN:(.*),SVCID:(.*),PID:(.*)',
        res[0])

    if match:

        details['sn'] = match.group(1)
        details['fn'] = match.group(2)
        details['svcid'] = match.group(3)
        details['pid'] = match.group(4)

        return details
Example #49
0
def getSNMP(ip,comm):
	oid = netsnmp.Varbind('iso.3.6.1.2.1.1.5.0')
	count = 0
	while (count < len(comm)):
		c = comm[count]
		sysname = netsnmp.snmpget(oid, Version = 2, DestHost = str(ip), Community = c, Timeout = 40000, Retries = 1)
		if (sysname[0]):
			break
		count += 1
	return(sysname[0])
def get_data(host, version, community, oid):
    try:
        var = netsnmp.Varbind(oid)
        data = netsnmp.snmpget(var, Version=version, DestHost=host, Community=community)
        value = data[0]
    except:
        helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='')
    if not value:
        helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='')
    return value
def VirDisk_Status():
    virdisk_status_oid = str(".1.3.6.1.4.1.674.10892.5.5.1.20.140.1.1.20.")
    virdisk_name_oid = str(".1.3.6.1.4.1.674.10892.5.5.1.20.140.1.1.36.")
    virdisk_name_list = []
    virdisk_status_list = []
    virdisk_problem_list = []
    virdisk_status_dict = {}

    for i in range(1, 8):
        virdisk_status_suboid = virdisk_status_oid + str(i)
        virdisk_status = netsnmp.snmpget(
            netsnmp.Varbind(virdisk_status_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(virdisk_status[0]) != str("None"):
            virdisk_status_list.append(virdisk_status[0])
        else:
            break

    for i in range(1, 8):
        virdisk_name_suboid = virdisk_name_oid + str(i)
        virdisk_name = netsnmp.snmpget(netsnmp.Varbind(virdisk_name_suboid),
                                       Version=2,
                                       DestHost=(hosts),
                                       Community=(communitys))
        if str(virdisk_name[0]) != str("None"):
            virdisk_name_list.append(virdisk_name[0])
        else:
            break

    virdisk_status_dict = dict(zip(virdisk_name_list, virdisk_status_list))

    for (k, i) in virdisk_status_dict.items():
        if i[0] != str(3):
            virdisk_problem_list.append(k)

    if len(virdisk_problem_list) == 0:
        print "All VirDisk is OK,",
    else:
        for i in virdisk_problem_list:
            print i,
        print "is problem,",
Example #52
0
def snmp():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v",
                        "--version",
                        help="version 1 or 2 or 3",
                        choices=[1, 2, 3],
                        type=int)
    parser.add_argument("-ip", "--ip", help="hostname/ip")
    parser.add_argument("-c", "--community", help="communit name")
    parser.add_argument("-u", "--v3_uname", help="v3 user name")
    parser.add_argument("-x", "--privprotocol", help="v3 priv protocol ex:AES")
    parser.add_argument("-X", "--privpassword", help="v3 priv password")
    parser.add_argument("-a", "--authprotocol", help="v3 auth protocol")
    parser.add_argument("-A", "--authpassword", help="v3 auth password")
    parser.add_argument("-l", "--level", help="v3 level")
    parser.add_argument("-o", "--oid", help="oid to get")
    try:
        args = parser.parse_args()
    except Exception:
        print "error in arguments passed"
    vars = netsnmp.Varbind(args.oid)
    snmpget = []
    if args.version == 2 or args.version == 1:
        snmp_get = netsnmp.snmpget(vars,
                                   Version=args.version,
                                   DestHost=args.ip,
                                   Community=args.community)
    if args.version == 3:
        snmp_get = netsnmp.snmpget(vars,
                                   Version=args.version,
                                   DestHost=args.ip,
                                   SecLevel=args.level,
                                   AuthProto=args.authprotocol,
                                   AuthPass=args.authpassword,
                                   PrivProto=args.privprotocol,
                                   PrivPass=args.privpassword,
                                   SecName=args.v3_uname)
    for j in snmp_get:
        snmpget.append(j)
        print j

    return snmpget
Example #53
0
def do_collect(hst, vrs, comm):
        port_list[hst] = []
        sock = socket.socket()
        try:
            sock.connect( (CARBON_SERVER,CARBON_PORT) )
        except:
            traceback.print_exc()
        now = int(time.time())
        args = {
            "Version": SNMP_VERSION,
            "DestHost": hst,
            "Community": comm
        }
        sess = netsnmp.Session (**args)
        INDEX_POS = 0
        MIB_ROOT = "ifIndex"
        MIB_CURR = MIB_ROOT
        RESULTS = {}
        while (MIB_ROOT == MIB_CURR):
            vars = netsnmp.VarList(netsnmp.Varbind(MIB_CURR,INDEX_POS))
            vals = sess.getbulk(0,16,vars)
            for i in vars:
                if (i.tag == MIB_CURR):
                    KEY = i.iid
                    RESULTS[KEY] = i
            INDEX_POS = int(vars[-1].iid)
            MIB_CURR = vars[-1].tag
        for idx in RESULTS:
            descr, oper, cin, cout = netsnmp.snmpget(
                netsnmp.Varbind("IF-MIB::ifDescr", idx),
                netsnmp.Varbind("IF-MIB::ifOperStatus", idx),
                netsnmp.Varbind("IF-MIB::ifHCInOctets", idx),
                netsnmp.Varbind("IF-MIB::ifHCOutOctets", idx),
                **args)
            assert(descr is not None and
                   cin is not None and
                   cout is not None) 
            if descr == "lo":
                continue
            if oper != "1":  
                continue
            skip = 0
            for term in IFACE_EXCEPT:
                if term in descr:
                    skip = 1
            if skip == 0:
                descr = descr.replace("/","-")
                descr = descr.replace("SuperBlade Gigabit Switch BMB-GEM-003, Port #","port-")
                port_list[hst].append(descr)
                graphiteMessage = GRAPHITE_PREFIX + "%s.if.%s-%s %s %d\n" % (hst,descr,"in",cin,now)
                sock.sendall(graphiteMessage)
                graphiteMessage = GRAPHITE_PREFIX + "%s.if.%s-%s %s %d\n" % (hst,descr,"out",cout,now)
                sock.sendall(graphiteMessage)
        sock.close()
Example #54
0
def poll_ifce(ifce):
    ifIndex = ifce['ifIndex']
    host = ifce['host']
    version = ifce['SNMP_VERSION']
    community = ifce['SNMP_COMMUNITY']
    ds = []
    for i, oid in enumerate(GRAPH_TYPES[ifce['type']]):
        snmpbind = netsnmp.Varbind('%s.%s'%(oid,ifIndex))
        result = netsnmp.snmpget(snmpbind, Version=version, DestHost='%s'%host, Community='%s'%community)[0]
        ds.append(result)
    return ds
Example #55
0
 def snmp_node(self,
               ipaddr,
               mac,
               vlan="1",
               oid="1.3.6.1.2.1.17.7.1.2.2.1.2"):
     oid = ".%s.%s.%s" % (oid, vlan, self.mac2dec(mac))
     res = netsnmp.snmpget(oid,
                           DestHost=ipaddr,
                           Version=1,
                           Community="public")
     return res
def SNMPGET(oid):
	VBoid = netsnmp.Varbind(oid)

	result = netsnmp.snmpget(oid, Version = int(options.version), DestHost=options.host, Community=options.community)[0]

	if result == None:
		back2nagios(RETURNCODE['UNKNOWN'], 'SNMP UNKNOWN: Timeout or no answer from %s' % options.host)

	if options.verb >= 1:
		print "%40s -> %s" %  (oid, result)

	return result
Example #57
0
    def test_v1_get(self):
        print "\n"
        print "---v1 GET tests -------------------------------------\n"
        var = netsnmp.Varbind('.1.3.6.1.2.1.1.1', '0')
        res = netsnmp.snmpget(var, **snmp_dest())

        print "v1 snmpget result: ", res, "\n"
        self.assertEqual(len(res), 1)

        print "v1 get var: ", var.tag, var.iid, "=", var.val, '(', var.type, ')'
        self.assertEqual(var.tag, 'sysDescr')
        self.assertEqual(var.iid, '0')
        self.assertEqual(var.val, res[0])
        self.assertEqual(var.type, 'OCTETSTR')
 def query(self):
     """Creates SNMP query
     
     Fills out a Host Object and returns result
     """
     try:
         result = netsnmp.snmpget(self.var,
                             Version = self.Version,
                             DestHost = self.DestHost,
                             Community = self.Community)
         self.hostrec.query = result
     except Exception, err:
         if self.Verbose:    
             print err
         self.hostrec.query = None