PyZabbix

1.3.1 · active · verified Tue Apr 14

PyZabbix provides a Python interface to the Zabbix API, allowing programmatic interaction with Zabbix monitoring systems. It handles API authentication, requests, and response parsing. The current version is 1.3.1, with releases occurring intermittently, often several months apart.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the Zabbix API, authenticate using either username/password or an API token (if provided via environment variables), retrieve basic Zabbix server information, and list hosts. It includes error handling for API-specific issues and ensures proper session cleanup with `logout()`.

import os
from pyzabbix import ZabbixAPI, ZabbixAPIException

# Configure Zabbix access via environment variables or replace directly
ZABBIX_URL = os.environ.get('ZABBIX_URL', 'http://localhost/zabbix') # e.g., 'http://your-zabbix-server/zabbix'
ZABBIX_USER = os.environ.get('ZABBIX_USER', 'Admin')
ZABBIX_PASSWORD = os.environ.get('ZABBIX_PASSWORD', 'zabbix') # Default 'zabbix' for Admin user
ZABBIX_TOKEN = os.environ.get('ZABBIX_TOKEN', '') # Optional: for API token authentication

# Initialize zapi outside try-block for finally access
zapi = None

try:
    # Connect to Zabbix API
    zapi = ZabbixAPI(ZABBIX_URL)

    if ZABBIX_TOKEN:
        # Authenticate using API token (requires Zabbix 5.0+ and pyzabbix >= 1.0.0)
        zapi.login(api_token=ZABBIX_TOKEN)
        print("Authenticated using API Token.")
    else:
        # Authenticate using username and password
        zapi.login(ZABBIX_USER, ZABBIX_PASSWORD)
        print(f"Authenticated as user: {ZABBIX_USER}")

    print(f"Connected to Zabbix API version: {zapi.api_version()}")

    # Example: Fetch Zabbix server info
    version_info = zapi.apiinfo.version()
    print(f"Zabbix Server Version: {version_info}")

    # Example: Fetch some hosts
    # 'output' determines which fields are returned, 'selectInterfaces' specifies linked data
    hosts = zapi.host.get(output='extend', selectInterfaces=['interfaceid', 'ip', 'port'])
    print(f"Found {len(hosts)} hosts.")
    if hosts:
        print(f"First host: {hosts[0]['host']} (IP: {hosts[0]['interfaces'][0]['ip']})")

except ZabbixAPIException as e:
    print(f"Error interacting with Zabbix API: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Ensure proper logout if authenticated
    if zapi and zapi.is_authenticated:
        zapi.logout()
        print("Logged out from Zabbix API.")

view raw JSON →