zabbix
Zabbix API curl
#LOGIN
curl -i -X POST -H 'Content-type:application/json' -d '{"jsonrpc":"2.0","method":"user.login","params":{ "user":"myUserName","password":"myPassword"},"auth":null,"id":0}' https://zabbix.server/api_jsonrpc.php
#GET ALL HOSTS WITH NAME
curl -i -X POST -H 'Content-type:application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output": ["hostid", "name"]},"auth":"<AUTH_KEY>","id":0}' https://zabbix.server/api_jsonrpc.php
#GET ALL HOSTS WITH NAME, HOSTNAME AND IP ADDRESS
curl -i -X POST -H 'Content-type:application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid", "host", "name"], "selectInterfaces":["ip"]},"auth":"<AUTH_KEY>","id":0}' https://zabbix.server/api_jsonrpc.php
Zabbix trigger hysteresis
Hysteresis, in the context of triggers and monitoring, describes a property of systems that do not instantly follow the variables they are responding to, but react slower or have a delayed output.
Essentially, in a monitoring system, hysteresis is implemented to prevent false trigger alarms, or "flapping", which is when a system rapidly alternates between states. This could occur, for example, if a measured value fluctuates around a threshold limit. Without hysteresis, each crossing of the threshold would trigger an alarm, leading to numerous unnecessary notifications.
By implementing hysteresis, you create a buffer, or a deadband, which means a set range that the value has to pass through before an alarm is triggered. This deadband has two thresholds: a set threshold for triggering the alarm and a reset threshold to stop the alarm. For instance, if you're monitoring internet uplink and you set the alarm threshold at 90% usage, you might set your reset threshold at 85%. The alarm won't stop until the usage drops below 85%, even if it briefly dips below 90%. This prevents the system from triggering a stop alarm immediately after it dips below 90% and then a start alarm when it inevitably goes back over 90%.
Zabbix delete unused templates
Python script that deletes unused templates via Zabbix API. You need API token for authentication in Zabbix. You need Python pyzabbix module.
#!/usr/bin/env python3
# Deletes unused Zabbix templates
# Requirements:
# - Python pyzabbix module
# - Zabbix access:
# - API token with admin access
from pyzabbix import ZabbixAPI
import yaml
import os
import json
import sys
zabbixURL = 'https://zabbix.example.com'
zabbixUser = 'zbxapi'
zabbixApiKey = '<Zabbix API token>'
# Connect to Zabbix API
zapi = ZabbixAPI(zabbixURL)
try:
zapi.login(api_token=zabbixApiKey)
except Exception as error:
print(f'zabbix_delete_templates.py [ERROR] zabbix login error: {error}')
sys.exit(1)
# Get all templates
try:
templates = zapi.template.get(output='extend', selectHosts='count', selectParentTemplates='count', selectTemplates='count')
except Exception as error:
print(f'zabbix_delete_templates.py [ERROR] get templates error: {error}')
sys.exit(1)
# Filter unused templates
unused_templates = [t for t in templates if t['hosts'] == "0" and t['parentTemplates'] == "0" and t['templates'] == "0"]
# print(json.dumps(unused_templates, indent=4))
# for template in unused_templates:
# print(template['name'])
# Export and delete unused templates
for template in unused_templates:
template_id = template['templateid']
template_name = template['name']
# Export template to YAML
export_data = zapi.configuration.export(format='yaml', options={'templates': [template_id]})
file_name = f"{template_name}.yaml"
try:
with open(file_name, 'w') as f:
f.write(export_data)
print(f"Exported {template_name} to {file_name}")
# Delete template
zapi.template.delete(template_id)
print(f"Deleted template {template_name}")
except Exception as error:
print(f"zabbix_delete_templates.py [ERROR] failed to export or delete template {template_name}: {error}")
sys.exit(1)
Zabbix get hosts with zero items
Python script that gets hosts with 0 items via Zabbix API. You need API token for authentication in Zabbix. You need Python pyzabbix module.
#!/usr/bin/env python3
# Gets Zabbix hosts with 0 items
# Requirements:
# - Python pyzabbix module
# - Zabbix access:
# - API token with admin access
from pyzabbix import ZabbixAPI
zabbix_api_url = "https://zabbix.example.com"
api_token = "<your-api-token>"
zapi = ZabbixAPI(zabbix_api_url)
zapi.login(api_token=api_token)
hosts = zapi.host.get(output=['hostid', 'name'])
hosts_with_zero_items = []
for host in hosts:
items = zapi.item.get(hostids=host['hostid'], countOutput=True)
if int(items) == 0: # Check if item count is 0
hosts_with_zero_items.append(host['name'])
# Print hosts with zero items
print("Hosts with 0 items:", hosts_with_zero_items)
Zabbix get hosts with zero groups
Python script that gets hosts with 0 groups via Zabbix API. You need API token for authentication in Zabbix. You need Python pyzabbix module.
#!/usr/bin/env python3
# Gets Zabbix hosts with 0 groups
# Requirements:
# - Python pyzabbix module
# - Zabbix access:
# - API token with admin access
from pyzabbix import ZabbixAPI
zabbix_api_url = "https://zabbix.example.com"
api_token = "<your-api-token>"
zapi = ZabbixAPI(zabbix_api_url)
zapi.login(api_token=api_token)
hosts = zapi.host.get(output=['hostid', 'host'], selectGroups='extend')
hosts_with_zero_groups = []
# Identify hosts that are not in any group
for host in hosts:
if not host['groups']: # Check if the 'groups' list is empty
hosts_with_zero_groups.append(host['host'])
# Print hosts with zero groups
print("Hosts with 0 groups:", hosts_with_zero_groups)
Zabbix get unsuported items
Python script that gets unsupported items via Zabbix API. You need API token for authentication in Zabbix. You need Python pyzabbix module.
#!/usr/bin/env python3
# Get Zabbix unsupported items
# Requirements:
# - Python pyzabbix module
# - Zabbix access:
# - API token with admin access
from pyzabbix import ZabbixAPI
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from time import time, sleep
from datetime import datetime
zabbixURL = 'https://zabbix.example.com'
zabbixApiKey = '<your-api-key>'
smtp_server = 'mxeu0.example.com'
sender_email = 'zabbix-outdated@example.com'
recipient_email = 'admin@example.com'
# Connect to Zabbix API
zapi = ZabbixAPI(zabbixURL)
try:
zapi.login(api_token=zabbixApiKey)
except Exception as error:
print(f'zabbix_delete_templates.py [ERROR] zabbix login error: {error}')
sys.exit(1)
one_day_ago = time() - 24*60*60
# Get enabled hosts
enabled_hosts = zapi.host.get(output=['hostid', 'host'], filter={'status': '0'})
subject = "Zabbix Outdated Items Report"
html = """
<html>
<body>
<p>List of outdated items from Zabbix (not updated in the last day):</p>
<table border="1" cellpadding="4" cellspacing="0" style="border-collapse: collapse;">
<tr>
<th>Hostname</th>
<th>Item Name</th>
<th>Last Check</th>
<th>Link</th>
</tr>
"""
outdated_items_found = False
for host in enabled_hosts:
host_id = host['hostid']
host_name = host['host']
# Get items for each enabled host
sleep(1)
host_items = zapi.item.get(output=['itemid', 'name', 'lastclock'], hostids=host_id, filter={'status': '0'})
for item in host_items:
if int(item['lastclock']) < one_day_ago:
outdated_items_found = True
item_name = item['name']
item_id = item['itemid']
last_check = datetime.fromtimestamp(int(item['lastclock'])).strftime('%Y-%m-%d %H:%M:%S')
item_link = f"{zabbixURL}/items.php?form=update&hostid={host_id}&itemid={item_id}&context=host"
html += f"""
<tr>
<td>{host_name}</td>
<td>{item_name}</td>
<td>{last_check}</td>
<td><a href="{item_link}">Link</a></td>
</tr>
"""
if not outdated_items_found:
html += """
<tr>
<td colspan="4">No outdated items found.</td>
</tr>
"""
html += """
</table>
</body>
</html>
"""
message = MIMEMultipart("alternative")
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(html, 'html'))
with smtplib.SMTP(smtp_server) as server:
server.send_message(message)
Zabbix hosts not in any specified groups
Python script that gets hosts not in any of specified group via Zabbix API. You need API token for authentication in Zabbix. You need Python pyzabbix module.
#!/usr/bin/env python3
# Gets Zabbix hosts with 0 groups
# Requirements:
# - Python pyzabbix module
# - Zabbix access:
# - API token with admin access
from pyzabbix import ZabbixAPI
# Initialize API connection
zapi = ZabbixAPI('https://zabbix.example.com')
zapi.login(api_token='<API-token>')
# Define group names to exclude
excluded_groups = {'Group1', 'Group2', 'Group3'}
# Retrieve all host groups and filter the desired ones
all_groups = zapi.hostgroup.get(output=['groupid', 'name'])
excluded_group_ids = [group['groupid'] for group in all_groups if group['name'] in excluded_groups]
# Retrieve all hosts not in the excluded groups
hosts = zapi.host.get(output=['hostid', 'host'], groupids=[group['groupid'] for group in all_groups], groupid_field='grp', selectGroups=['groupid'])
# Filter hosts not belonging to any of the excluded groups
hosts_not_in_excluded = [host for host in hosts if not any(group['groupid'] in excluded_group_ids for group in host['groups'])]
# Print the list of hosts
for host in hosts_not_in_excluded:
print(f"Host ID: {host['hostid']}, Host Name: {host['host']}")