def estimate_database_size(server, username, password, log_level,
                           template_name):
  zapi = ZabbixAPI(server=server, log_level=log_level)
  zapi.login(username, password)

  print ('Zabbix Server version: {}'.format(zapi.apiinfo.version({})))
  templates = zapi.template.get({'output': 'extend',
                                'filter': {'host': template_name}})
  if len(templates) == 0:
    print ('Unknown template "{}"'.format(template_name))
    sys.exit(1)
    return

  template = templates[0]
  templateid = template['templateid']

  items = zapi.item.get({'templateids': templateid, 'output': 'extend'})
  usage = 0
  for item in items:
    key_ = item['key_']
    refresh_rate = int(item['delay'])
    history = int(item['history'])
    trends = int(item['trends'])
    # print (key_, refresh_rate, history, trends)
    usage += ((history * (24.0 * 3600)) / refresh_rate) * 50
    usage += (24.0 * trends) * 128
    pass
    # print(key_, delay, history, trends)
  print ('{} MB'.format(usage / 1024 / 1024))
Exemple #2
0
def get_host_info(server, username, password, log_level):
  zapi = ZabbixAPI(server=server, log_level=log_level)
  zapi.login(username, password)

  responses = zapi.host.get({'output': 'extend'})
  
  hostid = responses[0]['hostid']
  items = zapi.item.get({'hostids': hostid, 'output': 'extend'})
  for item in items:
    if 'name' in item: # 2.0
      print('"{}" (id: {}):'.format(item['name'], item['itemid']))
    else: # 1.8
      print('"{}" (id: {}):'.format(item['description'], item['itemid']))
      pass
    pprint.pprint(item)
    pass
  pass
def add_item_to_host(server, username, password, log_level,
                     host, name, key, remove_duplicate=False):
  zapi = ZabbixAPI(server=server, log_level=log_level)
  zapi.login(username, password)

  version = zapi.apiinfo.version({})

  host_id = zapi.host.get({'filter': {'host': host}})[0]['hostid']
  duplicates = zapi.item.get({'filter': {'key_': key, 'host': host}})
  if len(duplicates) > 0:
    if remove_duplicate:
      print('Key "{}" already exists({}).'.format(key, duplicates))
      print('Try to remove it..')
      request = []
      for dup in duplicates:
        request.append(dup['itemid'])
        pass
      result = zapi.item.delete(request)['itemids']
      
      if type(result) == dict:
        # Seems a bug in 2.0.x, in which [{'itemids': {id: id}}] is returned.
        result = list(result.keys())
        pass

      if request != result:
        print('Requested ids ({}) and resultant ids ({}) don\'t match.'
              .format(request, result))
        sys.exit(1)
        return
      else:
        print('Delete operation seems successful.')
    else:
      print('Key "{}" already exists({}). Aborting..'.format(
          key, duplicates))
      sys.exit(1)
      return
    pass
  pass

  if version.startswith('2.2'):
    print('Not supported, yet.')
  elif version.startswith('2.0'):
    interfaceid = zapi.hostinterface.get({'hostids': host_id})
    try:
      # https://www.zabbix.com/documentation/2.0/manual/appendix/api/item/create
      result = zapi.item.create({ 'name' : name,
                                  'description' : 'description',
                                  'key_' : key,
                                  'type' : 0, # Zabbix agent
                                  'value_type': 0, # numeric float
                                  'hostid' : host_id,
                                  'interfaceid' : interfaceid[0]['interfaceid'],
                                  'delay' : 30,
                                  })
    except Already_Exists as e:
      print('Already exists')
      pass
    pass
  else: # 1.8, which returns '1.3'...
    # https://www.zabbix.com/documentation/1.8/api/item/create
    #
    # Note:
    #  - There's no "interfaceid" in 1.8
    #  - "name" isn't available but 'description is.
    #  - Already_Exists won't be returned even when it already exists.
    #  - Unkind errors will be sent on error, saying 
    #    "[ CItem::create ] Cannot create Item while sending .."
    result = zapi.item.create({ 'description' : name,
                                'key_' : key,
                                'hostid' : host_id,
                                'type' : 0, # Zabbix agent
                                'value_type': 0, # numeric float
                                'delay' : 30,
                                })
    pass
  print('Done.')
  pass
Exemple #4
0
def get_version(server, username, password, log_level):
  zapi = ZabbixAPI(server=server, log_level=log_level)
  zapi.login(username, password)
  return zapi.apiinfo.version({})
def get_item_stat(server, username, password, log_level, host, key):
  zapi = ZabbixAPI(server=server, log_level=log_level)
  zapi.login(username, password)

  item = zapi.item.get({ 'filter': {'host': host, 'key_': key},
                           'output': 'extend' })
  itemid = item[0]['itemid']

  print('item:')
  pprint.pprint(item)
  print('itemid: {}'.format(itemid))

  # If this is set too long, your Zabbix server may not respond well.
  now = time.time()
  time_from = int(now - 6*60*60)
  time_till = int(now)

  # See: https://www.zabbix.com/documentation/1.8/api/history/get
  #
  # All parameters are optional except "history".
  # If parameter is set in query, this option is considered
  # as being ON, except if parameter is equal to NULL.
  results = zapi.history.get({'history': 0, # Numeric (float)
                              'itemids': [itemid], 
                              'output': 'extend',
                              'time_from': time_from,
                              'time_till': time_till,
                              # 'limit': 300,
                              })

  if len(results) == 0:
    print('Empty result. Exitting')
    sys.exit(1)
    return

  (fd, filename) = tempfile.mkstemp(text=1)
  f = os.fdopen(fd, 'w')
  try:
    min_clock = -1
    max_clock = -1
    for result in results:
      clock = int(result['clock'])
      value = result['value']
      if min_clock < 0:
        min_clock = clock
      else:
        min_clock = min(clock, min_clock)
        pass
      if max_clock < 0:
        max_clock = clock
      else:
        max_clock = max(clock, max_clock)
        pass
      f.write('{} {}\n'.format(clock, value))
      pass
    min_t = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(min_clock))
    max_t = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(max_clock))
    print ('{} ({})-{} ({}) '.format(min_clock, min_t, max_clock, max_t))
    f.close()
    g = Gnuplot.Gnuplot()
    # g.set_range('yrange', (0,1))
    g.plot(Gnuplot.File(filename, using=(1,2), with_='lines'))
    raw_input('Press return to finish\n')
  finally:
    os.unlink(filename)
    pass
  pass
def add_item_to_host(server,
                     username,
                     password,
                     log_level,
                     host,
                     name,
                     key,
                     remove_duplicate=False):
    zapi = ZabbixAPI(server=server, log_level=log_level)
    zapi.login(username, password)

    version = zapi.apiinfo.version({})

    host_id = zapi.host.get({'filter': {'host': host}})[0]['hostid']
    duplicates = zapi.item.get({'filter': {'key_': key, 'host': host}})
    if len(duplicates) > 0:
        if remove_duplicate:
            print('Key "{}" already exists({}).'.format(key, duplicates))
            print('Try to remove it..')
            request = []
            for dup in duplicates:
                request.append(dup['itemid'])
                pass
            result = zapi.item.delete(request)['itemids']

            if type(result) == dict:
                # Seems a bug in 2.0.x, in which [{'itemids': {id: id}}] is returned.
                result = list(result.keys())
                pass

            if request != result:
                print(
                    'Requested ids ({}) and resultant ids ({}) don\'t match.'.
                    format(request, result))
                sys.exit(1)
                return
            else:
                print('Delete operation seems successful.')
        else:
            print('Key "{}" already exists({}). Aborting..'.format(
                key, duplicates))
            sys.exit(1)
            return
        pass
    pass

    if version.startswith('2.2'):
        print('Not supported, yet.')
    elif version.startswith('2.0'):
        interfaceid = zapi.hostinterface.get({'hostids': host_id})
        try:
            # https://www.zabbix.com/documentation/2.0/manual/appendix/api/item/create
            result = zapi.item.create({
                'name':
                name,
                'description':
                'description',
                'key_':
                key,
                'type':
                0,  # Zabbix agent
                'value_type':
                0,  # numeric float
                'hostid':
                host_id,
                'interfaceid':
                interfaceid[0]['interfaceid'],
                'delay':
                30,
            })
        except Already_Exists as e:
            print('Already exists')
            pass
        pass
    else:  # 1.8, which returns '1.3'...
        # https://www.zabbix.com/documentation/1.8/api/item/create
        #
        # Note:
        #  - There's no "interfaceid" in 1.8
        #  - "name" isn't available but 'description is.
        #  - Already_Exists won't be returned even when it already exists.
        #  - Unkind errors will be sent on error, saying
        #    "[ CItem::create ] Cannot create Item while sending .."
        result = zapi.item.create({
            'description': name,
            'key_': key,
            'hostid': host_id,
            'type': 0,  # Zabbix agent
            'value_type': 0,  # numeric float
            'delay': 30,
        })
        pass
    print('Done.')
    pass