CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-zabbix

Python module to work with Zabbix monitoring systems through API and sender functionality

Pending
Overview
Eval results
Files

api-interface.mddocs/

Zabbix API Interface

Complete Python interface to Zabbix's JSON-RPC API providing authentication management, dynamic method dispatch, and comprehensive error handling for all Zabbix monitoring operations including host management, configuration, and data retrieval.

Capabilities

ZabbixAPI Class

Main API client class that handles authentication, session management, and provides access to all Zabbix API methods through dynamic method dispatch.

class ZabbixAPI:
    def __init__(self, url=None, use_authenticate=False, use_basic_auth=False, user=None, password=None):
        """
        Initialize ZabbixAPI client.
        
        Parameters:
        - url (str, optional): Zabbix server URL (e.g., 'https://zabbix.example.com')
        - use_authenticate (bool, optional): Use user.authenticate instead of user.login (default: False)
        - use_basic_auth (bool, optional): Enable HTTP basic authentication (default: False)
        - user (str, optional): Username for authentication
        - password (str, optional): Password for authentication
        """

Authentication and Session Management

def api_version(self):
    """
    Get Zabbix API version.
    
    Returns:
    str: API version string
    """

def _login(self, user='', password=''):
    """
    Authenticate with Zabbix server (internal method).
    
    Parameters:
    - user (str, optional): Username (default: '')
    - password (str, optional): Password (default: '')
    
    Returns:
    None: Sets self.auth attribute with authentication token
    
    Raises:
    ZabbixAPIException: If authentication fails
    """

def _logout(self):
    """
    Logout from Zabbix server and invalidate session (internal method).
    
    Returns:
    bool: True if successful
    """

Core API Methods

def do_request(self, method, params=None):
    """
    Make raw JSON-RPC request to Zabbix API.
    
    Parameters:
    - method (str): API method name (e.g., 'host.get', 'user.login')
    - params (dict, optional): Method parameters
    
    Returns:
    dict: API response result
    
    Raises:
    ZabbixAPIException: If API returns error
    """

def get_id(self, item_type, item=None, with_id=False, hostid=None, **args):
    """
    Get object IDs by name or other criteria.
    
    Parameters:
    - item_type (str): Object type ('host', 'hostgroup', 'template', etc.)
    - item (str, optional): Object name to search for
    - with_id (bool, optional): Return full object data instead of just IDs
    - hostid (str, optional): Host ID for item-specific searches
    - **args: Additional filter parameters
    
    Returns:
    list: Object IDs or full object data
    """

Context Manager Support

def __enter__(self):
    """
    Context manager entry - returns self for with statements.
    
    Returns:
    ZabbixAPI: Self instance
    """

def __exit__(self, exc_type, exc_val, exc_tb):
    """
    Context manager exit - automatically logout on context exit.
    
    Parameters:
    - exc_type: Exception type (if any)
    - exc_val: Exception value (if any) 
    - exc_tb: Exception traceback (if any)
    """

Dynamic Method Access

The ZabbixAPI class provides dynamic access to all Zabbix API methods through attribute access:

def __getattr__(self, attr):
    """
    Provide dynamic access to API method groups.
    
    Parameters:
    - attr (str): API method group (e.g., 'host', 'user', 'item')
    
    Returns:
    ZabbixAPIObjectClass: Method dispatcher for the group
    """

ZabbixAPIObjectClass

Internal class that handles dynamic method dispatch for API method groups. Created automatically when accessing API method groups (e.g., zapi.host, zapi.user).

class ZabbixAPIObjectClass:
    def __init__(self, group, parent):
        """
        Initialize method group dispatcher.
        
        Parameters:
        - group (str): API method group name (e.g., 'host', 'user')
        - parent (ZabbixAPI): Parent ZabbixAPI instance
        """
    
    def __getattr__(self, name):
        """
        Dynamically create API method calls.
        
        Parameters:
        - name (str): API method name (e.g., 'get', 'create', 'update')
        
        Returns:
        function: Callable that executes the API method
        """

This class enables the fluent API pattern where zapi.host.get() translates to a host.get API call.

Usage Examples

Basic authentication and API calls:

from pyzabbix import ZabbixAPI, ZabbixAPIException

# Initialize and authenticate
zapi = ZabbixAPI('https://zabbix.example.com')
zapi.login('Admin', 'zabbix')

try:
    # Get API version
    version = zapi.api_version()
    print(f"Zabbix API version: {version}")
    
    # Get all hosts using dynamic method
    hosts = zapi.host.get(output='extend')
    
    # Get specific host by name
    host_id = zapi.get_id('host', 'server01')
    
    # Raw API request
    templates = zapi.do_request('template.get', {
        'output': ['templateid', 'name'],
        'sortfield': 'name'
    })
    
    # Create host group
    result = zapi.hostgroup.create(name='My Host Group')
    
except ZabbixAPIException as e:
    print(f"API Error: {e}")
finally:
    zapi.user.logout()

Using context manager for automatic logout:

from pyzabbix import ZabbixAPI

with ZabbixAPI('https://zabbix.example.com', user='Admin', password='zabbix') as zapi:
    # Get monitored hosts
    hosts = zapi.host.get(
        monitored_hosts=1,
        output=['hostid', 'host', 'name', 'status']
    )
    
    # Get items for a specific host
    items = zapi.item.get(
        hostids=hosts[0]['hostid'],
        output=['itemid', 'name', 'key_', 'lastvalue']
    )
    
    # Automatic logout when exiting context

Enabling logging for debugging:

import logging
import sys
from pyzabbix import ZabbixAPI

# Configure logging
logger = logging.getLogger("pyzabbix")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)

zapi = ZabbixAPI('https://zabbix.example.com', user='Admin', password='zabbix')
# Requests and responses will be logged (with passwords masked)
hosts = zapi.host.get(output='extend')

Error Handling

class ZabbixAPIException(Exception):
    """
    Custom exception for Zabbix API errors.
    
    Attributes:
    - error (dict): Full error details from API response
    - message (str): Error message
    - code (int): Error code
    - data (str): Additional error data
    - json (str): Sanitized JSON request (passwords masked)
    """
    def __init__(self, error):
        """
        Initialize exception with error details.
        
        Parameters:
        - error (dict): Error information from API response
        """

Common error codes:

  • 32602: Invalid params (e.g., object already exists)
  • 32500: No permissions
  • -32602: Invalid method parameters
  • -32500: Application error (user not logged in, permission denied)

API Method Groups

The ZabbixAPI class provides access to all Zabbix API method groups through dynamic attributes:

  • zapi.host.* - Host management (get, create, update, delete)
  • zapi.hostgroup.* - Host group management
  • zapi.item.* - Item management
  • zapi.trigger.* - Trigger management
  • zapi.user.* - User management (login, logout, get, create)
  • zapi.template.* - Template management
  • zapi.graph.* - Graph management
  • zapi.action.* - Action management
  • zapi.alert.* - Alert management
  • zapi.event.* - Event management
  • zapi.maintenance.* - Maintenance management
  • zapi.map.* - Network map management
  • zapi.screen.* - Screen management
  • zapi.script.* - Script management
  • zapi.service.* - IT service management
  • zapi.mediatype.* - Media type management
  • zapi.proxy.* - Proxy management

Each method group supports the standard CRUD operations where applicable (get, create, update, delete) plus method-specific operations.

Utility Functions

@staticmethod
def cred_to_base64(user, password):
    """
    Create base64-encoded credentials for HTTP basic authentication.
    
    Parameters:
    - user (str): Username
    - password (str): Password
    
    Returns:
    str: Base64-encoded credentials string
    """

def ssl_context_compat(func):
    """
    Decorator to handle SSL context compatibility across Python versions.
    
    This decorator wraps urllib functions to disable SSL certificate verification
    for self-signed certificates, handling version differences between Python 2.7.9+
    and Python 3.4.3+.
    
    Parameters:
    - func (function): Function to wrap (typically urllib2.urlopen)
    
    Returns:
    function: Wrapped function with SSL context handling
    """

These utilities support advanced authentication scenarios and SSL handling across different Python versions.

Install with Tessl CLI

npx tessl i tessl/pypi-py-zabbix

docs

api-interface.md

index.md

metric-sending.md

tile.json