zabbix:zabbix部分api封装

import requests
import json
import sys
import os


class ZabbixAPI(object):
    # https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/get
    _auth = None
    _cur_job_id = 0
    _job_id = 0
    _headers = {
        'Content-Type': 'application/json-rpc'
    }

    def __init__(self, user, password, domain):
        """
        :param user:
        :param password:
        :param domain: http://nmst.lenovo.com/
        Usage:
            # >>> user = 'Admin'
            # >>> password = 'zabbix'
            # >>> domain = 'http://nmst.lenovo.com/'
            # >>> z_api = ZabbixAPI(user, password, domain)
            # >>> print(z_api.map.get())
        """
        self.user = user
        self.password = password
        if 'api_jsonrpc.php' not in domain:
            self.base_url = os.path.join(domain, 'api_jsonrpc.php').replace('\\', '/')
        else:
            self.base_url = domain

        self.alert = self.Alert(self)
        self.application = self.Application(self)
        self.event = self.Event(self)
        self.host = self.Host(self)
        self.hostgroup = self.HostGroup(self)
        self.hostinterface = self.HostInterface(self)
        self.item = self.Item(self)
        self.maintenance = self.Maintenance(self)
        self.map = self.Map(self)
        self.problem = self.Problem(self)
        self.proxy = self.Proxy(self)
        self.template = self.Template(self)
        self.trigger = self.Trigger(self)
        self.history = self.History(self)

    @property
    def job_id(self):
        self._cur_job_id = self._job_id
        self._job_id += 1
        return self._job_id

    @property
    def auth(self):
        if not self._auth:
            data = {
                'jsonrpc': '2.0',
                'method': 'user.login',
                'params': {
                    'user': self.user,
                    'password': self.password
                },
                'id': self.job_id,
                'auth': None
            }
            with requests.post(self.base_url, data=json.dumps(data), headers=self._headers) as response:
                result = response.json()
                if result.get('error'):
                    raise Exception(result.get('error'))
                self._auth = result.get('result')
        return self._auth

    def post(self, method, params):
        data = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params,
            'auth': self.auth,
            'id': self.job_id
        }
        with requests.post(self.base_url, data=json.dumps(data), headers=self._headers) as response:
            return response.json()

    class Alert(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/alert/get
            :param params:  {
                "output": "extend",
                "actionids": "3"
            }
            alertids        string/array    Return only alerts with the given IDs.
            actionids        string/array    Return only alerts generated by the given actions.
            eventids        string/array    Return only alerts generated by the given events.
            groupids        string/array    Return only alerts generated by objects from the given host groups.
            hostids            string/array    Return only alerts generated by objects from the given hosts.
            mediatypeids    string/array    Return only message alerts that used the given media types.
            objectids        string/array    Return only alerts generated by the given objects
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Application(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/application/get
            :param params:
            applicationids    string/array    Return only applications with the given IDs.
            groupids        string/array    Return only applications that belong to hosts from the given host groups.
            hostids            string/array    Return only applications that belong to the given hosts.
            inherited        boolean    If set to true return only applications inherited from a template.
            itemids            string/array    Return only applications that contain the given items.
            templated        boolean    If set to true return only applications that belong to templates.
            templateids        string/array    Return only applications that belong to the given templates.
            selectHost        query    Return the host that the application belongs to in the host property.
            selectItems        query    Return the items contained in the application in the items property.
            selectDiscoveryRule            query    Return the LLD rule that created the application in the discoveryRule property.
            selectApplicationDiscovery    query    Return the application discovery object in the applicationDiscovery property.
            sortfield                    string/array    Sort the result by the given properties.
                                        Possible values are: applicationid and name.

            countOutput        boolean    These parameters being common for all get methods are described in detail in the
                            reference commentary page.
            editable        boolean
            excludeSearch    boolean
            filter            object
            limit            integer
            output            query
            preservekeys    boolean
            search            object
            searchByAny        boolean
            searchWildcardsEnabled    boolean
            sortorder                string/array
            startSearch                boolean
            "params": {
                "output": "extend",
                "hostids": "10001",
                "sortfield": "name"
            }
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, application_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/application/delete
            :param application_ids:
            "application_ids": [
                "356",
                "358"
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=[str(_id) for _id in application_ids])

        def create(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/application/create
            :param params:
            "params": {
                "name": "SNMP Items",
                "hostid": "10050"
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/application/update
            :param params:
            "params": {
                "applicationid": "13",
                "name": "Processes and performance"
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def massadd(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/application/massadd
            :param params:
            applications(required)    array/object    Applications to be updated.
                                                    The applications must have the applicationid property defined.
            items                    array/object    Items to add to the given applications.
                                                    The items must have the itemid property defined.
            "params": {
                "applications": [
                    {
                        "applicationid": "247"
                    },
                    {
                        "applicationid": "246"
                    }
                ],
                "items": [
                    {
                        "itemid": "22800"
                    },
                    {
                        "itemid": "22801"
                    }
                ]
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Event(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/event/get
            :param params: {
                "output": "extend",
                "select_acknowledges": "extend",
                "selectTags": "extend",
                "selectSuppressionData": "extend",
                "objectids": "13926",
                "sortfield": ["clock", "eventid"],
                "sortorder": "DESC"
            }
            eventids        string/array    Return only events with the given IDs.
            groupids        string/array    Return only events created by objects that belong to the given host groups.
            hostids            string/array    Return only events created by objects that belong to the given hosts.
            objectids        string/array    Return only events created by the given objects.
            applicationids    string/array    Return only events created by objects that belong to the given applications.
                                            Applies only if object is trigger or item.
            :return:
            """
            params.update(output='extend', sortfield=['clock', 'eventid'], sortorder='DESC')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Host(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/host/get
            :param params:  {
                "filter": {
                    "host": [
                        "Zabbix server",
                        "Linux server"
                    ]
                }
            }
            groupids            string/array    Return only hosts that belong to the given groups.
            applicationids        string/array    Return only hosts that have the given applications.
            dserviceids            string/array    Return only hosts that are related to the given discovered services.
            graphids            string/array    Return only hosts that have the given graphs.
            hostids                string/array    Return only hosts with the given host IDs.
            httptestids            string/array    Return only hosts that have the given web checks.
            interfaceids        string/array    Return only hosts that use the given interfaces.
            itemids                string/array    Return only hosts that have the given items.
            maintenanceids        string/array    Return only hosts that are affected by the given maintenances.
            monitored_hosts        flag            Return only monitored hosts.
            proxy_hosts            flag            Return only proxies.
            proxyids            string/array    Return only hosts that are monitored by the given proxies.
            templated_hosts        flag            Return both hosts and templates.
            templateids            string/array    Return only hosts that are linked to the given templates.
            triggerids            string/array    Return only hosts that have the given triggers.
            with_items            flag            Return only hosts that have items. Overrides the
                                                with_monitored_items and with_simple_graph_items parameters.

            with_applications    flag            Return only hosts that have applications.
            with_graphs            flag            Return only hosts that have graphs.
            with_httptests        flag            Return only hosts that have web checks.
                                                Overrides the with_monitored_httptests parameter.

            with_monitored_httptests    flag    Return only hosts that have enabled web checks.
            with_monitored_items        flag    Return only hosts that have enabled items.
                                                Overrides the with_simple_graph_items parameter.

            with_monitored_triggers        flag    Return only hosts that have enabled triggers. All of the items used in
                                                the trigger must also be enabled.

            with_simple_graph_items        flag    Return only hosts that have items with numeric type of information.
            with_triggers                flag    Return only hosts that have triggers.
                                                Overrides the with_monitored_triggers parameter.
            withInventory                flag    Return only hosts that have inventory data.
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/host/update
            :param params: {
                "hostid": "10126",
                "status": 0,
                ...
            }
            groups            object/array    Host groups to replace the current host groups the host belongs to.
                                            The host groups must have the groupid property defined.
                                            All host groups that are not listed in the request will be unlinked.

            interfaces        object/array    Host interfaces to replace the current host interfaces.
                                            All interfaces that are not listed in the request will be removed.

            inventory        object            Host inventory properties.
            macros            object/array    User macros to replace the current user macros.
                                            All macros that are not listed in the request will be removed.

            templates        object/array    Templates to replace the currently linked templates.
                                            All templates that are not listed in the request will be only unlinked.
                                            The templates must have the templateid property defined.

            templates_clear    object/array    Templates to unlink and clear from the host.
                                            The templates must have the templateid property defined.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def massupdate(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/host/massupdate
            :param params: {
                "hosts": [
                    {
                        "hostid": "69665"
                    },
                    {
                        "hostid": "69666"
                    },
                ],
                "status": 0,
                ...
            }
            hosts (required)    object/array    Hosts to be updated.
                                                The hosts must have the hostid property defined.
            groups                object/array    Host groups to replace the current host groups the hosts belong to.
                                                The host groups must have the groupid property defined.
            interfaces            object/array    Host interfaces to replace the current host interfaces on the given hosts.
            inventory            object            Host inventory properties.
                                                Host inventory mode cannot be updated using the inventory parameter,
                                                use inventory_mode instead.

            inventory_mode        integer            Host inventory population mode. Refer to the host inventory object
                                                page for a list of supported inventory modes.

            macros                object/array    User macros to replace the current user macros on the given hosts.
            templates            object/array    Templates to replace the currently linked templates on the given hosts.
                                                The templates must have the templateid property defined.

            templates_clear        object/array    Templates to unlink and clear from the given hosts.
                                                The templates must have the templateid property defined.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, host_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/host/delete
            :param host_ids: [
                "13",
                "32",
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=host_ids)

        def create(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/host/create
            :param ip:
            :param hostname:
            :param i_type:  One of ('AGENT', 'SNMP', 'IPMI', 'JMX'), default 'SNMP'
            :param groups: [{"groupid": group_id}]
            :param template_ids: str or list
            :param port:
            :param use_ip: 0 -connect using host DNS name; 1 -connect using host IP address for this host interface.
            :param dns:
            :param bulk: Whether to use bulk SNMP requests. 0-don't use bulk requests;  1-(default) use bulk requests.
            :param inventory: dict
            :param macros: list
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            result = self._parent.post(method=method, params=params)
            result.update(hostname=params.get('host'), groups=params.get('groups'))
            return result

    class HostGroup(object):
        def __init__(self, parent):
            self._parent = parent

        def create(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/create
            :param params: {
                "name": "Linux servers",
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, group_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/delete
            :param group_ids: [
                '124',
                '125'
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=group_ids)

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/get
            :param params:  {
                "filter": {
                    "name": [
                        "Zabbix servers",
                        "Linux servers"
                    ]
                }
            }
            graphids            string/array    Return only host groups that contain hosts or templates with the
                                                given graphs.
            groupids            string/array    Return only host groups with the given host group IDs.
            hostids                string/array    Return only host groups that contain the given hosts.
            maintenanceids        string/array    Return only host groups that are affected by the given maintenances.
            monitored_hosts        flag            Return only host groups that contain monitored hosts.
            real_hosts            flag            Return only host groups that contain hosts.
            templated_hosts        flag            Return only host groups that contain templates.
            templateids            string/array    Return only host groups that contain the given templates.
            triggerids            string/array    Return only host groups that contain hosts or templates with the
                                                given triggers.
            with_applications            flag    Return only host groups that contain hosts with applications.
            with_graphs                    flag    Return only host groups that contain hosts with graphs.
            with_hosts_and_templates    flag    Return only host groups that contain hosts or templates.
            with_httptests                flag    Return only host groups that contain hosts with web checks.
                                                Overrides the with_monitored_httptests parameter.

            with_items                    flag    Return only host groups that contain hosts or templates with items.
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def massadd(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/massadd
            :param {
                "groups": [
                    {
                        "groupid": "5"
                    },
                    {
                        "groupid": "6"
                    },
                ],
                "hosts": [
                    {
                        "hostid": "30050"
                    },
                    {
                        "hostid": "30001"
                    }
                ]
            }
            groups(required)    object/array    Host groups to be updated.
                                                The host groups must have the groupid property defined.

            hosts                object/array    Hosts to add to all host groups.
                                                The hosts must have the hostid property defined.

            templates            object/array    Templates to add to all host groups.
                                                The templates must have the templateid property defined.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class HostInterface(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostinterface/get
            :param params:
            {
                "output": "extend",
                "hostids": "30057"
            }
            hostids            string/array    Return only host interfaces used by the given hosts.
            interfaceids    string/array    Return only host interfaces with the given IDs.
            itemids            string/array    Return only host interfaces used by the given items.
            triggerids        string/array    Return only host interfaces used by items in the given triggers.
            selectItems        query            Return the items that use the interface in the items property.
                                            Supports count.

            selectHosts        query            Return the host that uses the interface as an array in the hosts property.
            limitSelects    integer            Limits the number of records returned by subselects.
                                            Applies to the following subselects: selectItems.

            sortfield        string/array    Sort the result by the given properties.
                                            Possible values are: interfaceid, dns, ip.
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/hostinterface/update
            :param params: {
                "interfaceid": "30048",
                "port": "30050"
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, interface_ids):
            """
            :param interface_ids:  [
                "30062"
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=interface_ids)

    class Item(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/item/get
            :param params: {
                "output": "extend",
                "hostids": "10084",
                "search": {
                    "key_": "system"
                },
                "sortfield": "name",
                ...
            }
            itemids            string/array    Return only items with the given IDs.
            groupids        string/array    Return only items that belong to the hosts from the given groups.
            templateids        string/array    Return only items that belong to the given templates.
            hostids            string/array    Return only items that belong to the given hosts.
            proxyids        string/array    Return only items that are monitored by the given proxies.
            interfaceids    string/array    Return only items that use the given host interfaces.
            graphids        string/array    Return only items that are used in the given graphs.
            triggerids        string/array    Return only items that are used in the given triggers.
            applicationids    string/array    Return only items that belong to the given applications.
            webitems        flag    Include web items in the result.
            inherited        boolean    If set to true return only items inherited from a template.
            templated        boolean    If set to true return only items that belong to templates.
            monitored        boolean    If set to true return only enabled items that belong to monitored hosts.
            group            string    Return only items that belong to a group with the given name.
            host            string    Return only items that belong to a host with the given name.
            application        string    Return only items that belong to an application with the given name.
            with_triggers    boolean    If set to true return only items that are used in triggers.
            ...
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, item_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/template/delete
            :param item_ids: [
                "13",
                "32"
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=item_ids)

    class Maintenance(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/maintenance/get
            :param params:
            groupids        string/array        Return only maintenances that are assigned to the given host groups.
            hostids            string/array        Return only maintenances that are assigned to the given hosts.
            maintenanceids    string/array        Return only maintenances with the given IDs.
            selectGroups    query                Return host groups assigned to the maintenance in the groups property.
            selectHosts        query                Return hosts assigned to the maintenance in the hosts property.
            selectTimeperiods    query            Return the maintenance's time periods in the timeperiods property.
            selectTags            query            Return the maintenance's problem tags in the tags property.
            sortfield            string/array    Sort the result by the given properties.

            Possible values are: maintenanceid, name and maintenance_type.
            :return:
            """
            params.update(output='extend', selectTags='extend', selectGroups='extend', selectTimeperiods='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, maintenance_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/maintenance/delete
            :param maintenance_ids: ['1', '2']
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=maintenance_ids)

        def create(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/maintenance/create
            :param params: {
                "name": "Sunday maintenance",
                "active_since": 1358844540,
                "active_till": 1390466940,
                "tags_evaltype": 0,
                "groupids": [
                    "2"
                ],
                "timeperiods": [
                    {
                        "timeperiod_type": 3,
                        "every": 1,
                        "dayofweek": 64,
                        "start_time": 64800,
                        "period": 3600
                    }
                ],
                "tags": [
                    {
                        "tag": "service",
                        "operator": "0",
                        "value": "mysqld",
                    },
                    {
                        "tag": "error",
                        "operator": "2",
                        "value": ""
                    }
                ]
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Map(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/map/get
            :param params:
            sysmapids        string/array    Return only maps with the given IDs.
            userids            string/array    Return only maps that belong to the given user IDs.
            expandUrls        flag    Adds global map URLs to the corresponding map elements and expands macros in all map element URLs.
            selectIconMap    query    Returns the icon map used on the map in the iconmap property.
            selectLinks        query    Returns map links between elements in the links property.
            selectSelements    query    Returns the map elements from the map in the selements property.
            selectUrls        query    Returns the map URLs in the urls property.
            selectUsers        query    Returns users that the map is shared with in users property.
            selectUserGroups    query    Returns user groups that the map is shared with in userGroups property.
            selectShapes        query    Returns the map shapes from the map in the shapes property.
            selectLines            query    Returns the map lines from the map in the lines property.
            sortfield            string/array    Sort the result by the given properties.
                                                Possible values are: name, width and height.

            countOutput            boolean    These parameters being common for all get methods are described in detail in the reference commentary.
            editable        boolean
            excludeSearch    boolean
            filter            object
            limit            integer
            output            query
            preservekeys    boolean
            search            object
            searchByAny        boolean
            searchWildcardsEnabled    boolean
            sortorder                string/array
            startSearch                boolean
            :return:
            """
            params.update(
                output='extend', selectSelements='extend',
                selectLinks='extend', selectUsers='extend',
                selectUserGroups='extend', selectShapes='extend',
                selectLines='extend'
            )
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/map/update
            :param params: {
                "sysmapid": "8",
                "width": 1200,
                "height": 1200
            }
            links        array    Map liks to replace the existing links.
            selements    array    Map elements to replace the existing elements.
            urls        array    Map URLs to replace the existing URLs.
            users        array    Map user shares to replace the existing elements.
            userGroups    array    Map user group shares to replace the existing elements.
            shapes        array    Map shapes to replace the existing shapes.
            lines        array    Map lines to replace the existing lines.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, map_ids):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/map/delete
            :param map_ids: ['1', '2']
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=[str(map_id) for map_id in map_ids])

        def create(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/map/create
            :param params:
            links        array    Map links to be created on the map.
            selements    array    Map elements to be created on the map.
            urls        array    Map URLs to be created on the map.
            users        array    Map user shares to be created on the map.
            userGroups    array    Map user group shares to be created on the map.
            shapes        array    Map shapes to be created on the map.
            lines        array    Map lines to be created on the map.

            "params": {
                "name": "Host map",
                "width": 600,
                "height": 600,
                "selements": [
                    {
                        "selementid": "1",
                        "elements": [
                            {"hostid": "1033"}
                        ],
                        "elementtype": 0,
                        "iconid_off": "2"
                    },

                    {
                        "selementid": "2",
                        "elements": [
                            {"hostid": "1037"}
                        ],
                        "elementtype": 0,
                        "iconid_off": "2"
                    }
                ],
                "links": [
                    {
                        "selementid1": "1",
                        "selementid2": "2"
                    }
                ]
            }
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Problem(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/problem/get
            :param params: {
                "output": "extend",
                "selectAcknowledges": "extend",
                "selectTags": "extend",
                "selectSuppressionData": "extend",
                "objectids": "15112",
                "recent": "true",
                "sortfield": ["eventid"],
                "sortorder": "DESC"
            }
            eventids        string/array    Return only problems with the given IDs.
            groupids        string/array    Return only problems created by objects that belong to the given host groups.
            hostids            string/array    Return only problems created by objects that belong to the given hosts.
            objectids        string/array    Return only problems created by the given objects.
            applicationids    string/array    Return only problems created by objects that belong to the given applications.
                                            Applies only if object is trigger or item.
            ...
            :return:
            """
            params.update(output='extend', selectTags='extend', selectSuppressionData='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Proxy(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/proxy/get
            :params: {
                "output": "extend",
                "selectInterface": "extend",
                "proxyids": [
                    "1212"
                ],
            }
            proxyids        string/array    Return only proxies with the given IDs.
            selectHosts        query            Return hosts monitored by the proxy in the hosts property.
            selectInterface    query            Return the proxy interface used by a passive proxy in the interface property.
            sortfield        string/array    Sort the result by the given properties.
                                            Possible values are: hostid, host and status.
            :return:
            """
            params.update(output='extend', selectInterface='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/proxy/update
            :param params: {
                "proxyid": "1010",
                "hosts": [
                    "12441",
                    "14221",
                ]
            }
            hosts        array    Hosts to be monitored by the proxy. If a host is already monitored by a different proxy,
                                it will be reassigned to the current proxy.
                                The hosts must have the hostid property defined.

            interface    object    Host interface to replace the existing interface for the passive proxy.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, **params):
            """
            :param params:  [
                "10286",
                "10285"
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Template(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/template/get
            :param params: {
                "filter": {
                    "host": [
                        "Template OS Linux",
                        "Template OS Windows"
                    ]
                }
            }
            templateids            string/array    Return only templates with the given template IDs.
            groupids            string/array    Return only templates that belong to the given host groups.
            parentTemplateids    string/array    Return only templates that are children of the given templates.
            hostids                string/array    Return only templates that are linked to the given hosts.
            graphids            string/array    Return only templates that contain the given graphs.
            itemids                string/array    Return only templates that contain the given items.
            triggerids            string/array    Return only templates that contain the given triggers.
            with_items            flag    Return only templates that have items.
            with_triggers        flag    Return only templates that have triggers.
            with_graphs            flag    Return only templates that have graphs.
            with_httptests        flag    Return only templates that have web scenarios.
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def update(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/template/update
            :param params: {
                "templateid": "10086",
                "name": "Template OS Linux"
            }
            groups            object/array    Host groups to replace the current host groups the templates belong to.
                                            The host groups must have the groupid property defined.

            hosts            object/array    Hosts and templates to replace the ones the templates are currently linked to.
                                            Both hosts and templates must use the hostid property to pass an ID.

            macros            object/array    User macros to replace the current user macros on the given templates.

            templates        object/array    Templates to replace the currently linked templates.
                                            Templates that are not passed are only unlinked.
                                            The templates must have the templateid property defined.

            templates_clear    object/array    Templates to unlink and clear from the given templates.
                                            The templates must have the templateid property defined.
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

        def delete(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/template/delete
            :param params:  [
                "13",
                "32"
            ]
            :return:
            """
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class Trigger(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/trigger/get
            :param params: {
                "triggerids": "14062",
                "output": "extend",
                "selectFunctions": "extend"
            }
            triggerids        string/array    Return only triggers with the given IDs.
            groupids        string/array    Return only triggers that belong to hosts from the given host groups.
            templateids        string/array    Return only triggers that belong to the given templates.
            hostids            string/array    Return only triggers that belong to the given hosts.
            itemids            string/array    Return only triggers that contain the given items.
            applicationids    string/array    Return only triggers that contain items from the given applications.
            :return:
            """
            params.update(output='extend', selectFunctions='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)

    class History(object):
        def __init__(self, parent):
            self._parent = parent

        def get(self, **params):
            """
            https://www.zabbix.com/documentation/5.0/manual/api/reference/history/get
            :param params: {
                "itemids": "2878951",
                "output": "extend"
            }
            history        integer            History object types to return.
                                        Possible values:
                                        0 - numeric float;
                                        1 - character;
                                        2 - log;
                                        3 - numeric unsigned;
                                        4 - text.
                                        Default: 3.
            hostids        string/array    Return only history from the given hosts.
            itemids        string/array    Return only history from the given items.
            time_from    timestamp        Return only values that have been received after or at the given time.
            time_till    timestamp        Return only values that have been received before or at the given time.
            sortfield    string/array    Sort the result by the given properties.
                                        Possible values are: itemid and clock.
            countOutput    boolean            These parameters being common for all get methods are described in detail
                                        in the reference commentary page.
            editable    boolean
            excludeSearch    boolean
            filter            object
            limit            integer
            output            query
            search            object
            searchByAny     boolean
            searchWildcardsEnabled    boolean
            sortorder        string/array
            startSearch     boolean
            :return:
            """
            params.update(output='extend')
            method = '.'.join([self.__class__.__name__.lower(), sys._getframe().f_code.co_name]).lower()
            return self._parent.post(method=method, params=params)


if __name__ == '__main__':
    z_api = ZabbixAPI(
        user='user',
        password='password',
        domain='http://nmst.lenovo.com/api_jsonrpc.php'
    )
    res = z_api.history.get(
        itemids='2879009',  # time_from='', time_till='',
        sortfield='clock', limit=10, sortorder='DESC'
    )
    print(json.dumps(res, indent=4))

 

posted @ 2021-01-06 17:36  士为知己  阅读(153)  评论(0)    收藏  举报