Giter VIP home page Giter VIP logo

pyzabbix's Introduction

PyZabbix

PyZabbix is a Python module for working with the Zabbix API.

CI PyPI Package Version PyPI Python Versions

Requirements

  • Tested against Zabbix 4.0 LTS, 5.0 LTS, 6.0 LTS and 6.4.

Documentation

Note

If you are looking for a Zabbix Sender, please use the zappix library.

Getting Started

Install PyZabbix using pip:

$ pip install pyzabbix

You can now import and use pyzabbix like so:

from pyzabbix import ZabbixAPI

zapi = ZabbixAPI("http://zabbixserver.example.com")
zapi.login("zabbix user", "zabbix pass")
# You can also authenticate using an API token instead of user/pass with Zabbix >= 5.4
# zapi.login(api_token='xxxxx')
print("Connected to Zabbix API Version %s" % zapi.api_version())

for h in zapi.host.get(output="extend"):
    print(h['hostid'])

Refer to the Zabbix API Documentation and the PyZabbix Examples for more information.

Customizing the HTTP request

PyZabbix uses the requests library for HTTP. You can customize the request parameters by configuring the requests Session object used by PyZabbix.

This is useful for:

  • Customizing headers
  • Enabling HTTP authentication
  • Enabling Keep-Alive
  • Disabling SSL certificate verification
from pyzabbix import ZabbixAPI

zapi = ZabbixAPI("http://zabbixserver.example.com")

# Enable HTTP auth
zapi.session.auth = ("http user", "http password")

# Disable SSL certificate verification
zapi.session.verify = False

# Specify a timeout (in seconds)
zapi.timeout = 5.1

# Login (in case of HTTP Auth, only the username is needed, the password, if passed, will be ignored)
zapi.login("http user", "http password")

# You can also authenticate using an API token instead of user/pass with Zabbix >= 5.4
# zapi.login(api_token='xxxxx')

Enabling debug logging

If you need to debug some issue with the Zabbix API, you can enable the output of logging, pyzabbix already uses the default python logging facility but by default, it logs to "Null", you can change this behavior on your program, here's an example:

import sys
import logging
from pyzabbix import ZabbixAPI

stream = logging.StreamHandler(sys.stdout)
stream.setLevel(logging.DEBUG)
log = logging.getLogger('pyzabbix')
log.addHandler(stream)
log.setLevel(logging.DEBUG)


zapi = ZabbixAPI("http://zabbixserver.example.com")
zapi.login('admin','password')

# You can also authenticate using an API token instead of user/pass with Zabbix >= 5.4
# zapi.login(api_token='xxxxx')

The expected output is as following:

Sending: {
    "params": {
        "password": "password",
        "user": "admin"
    },
    "jsonrpc": "2.0",
    "method": "user.login",
    "id": 2
}
Response Code: 200
Response Body: {
    "jsonrpc": "2.0",
    "result": ".................",
    "id": 2
}
>>>

Development

To develop this project, start by reading the Makefile to have a basic understanding of the possible tasks.

Install the project and the dependencies in a virtual environment:

make install
source .venv/bin/activate

License

LGPL 2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html

Zabbix API Python Library.

Original Ruby Library is Copyright (C) 2009 Andrew Nelson nelsonab(at)red-tux(dot)net

Original Python Library is Copyright (C) 2009 Brett Lentz brett.lentz(at)gmail(dot)com

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

pyzabbix's People

Contributors

bitphage avatar bladealslayer avatar blin avatar bmanojlovic avatar colttt avatar dmiyakawa avatar ekohl avatar garlandkr avatar github-actions[bot] avatar greenmoon55 avatar jooola avatar lukecyca avatar manuel-domke avatar maxgrechnev avatar neothematrix avatar nvitaly avatar paalbra avatar pheanex avatar ratevuloire avatar rrtj3 avatar simoon78 avatar spindel avatar stefanverhoeff avatar syphernl avatar szuro avatar taroguru avatar the-01 avatar vphilippon avatar wagptech avatar zbal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyzabbix's Issues

How to add item to template

zapi.create.item(hostid=24363,
key_="service.status[mysql,unflushed_log,{$HOST}/{$PORT},{$USER}/{$PASSWD}]",
name="{$HOST}:{$PORT} Mysql Unflushed Log",
delay=60,
value_type=3,
units='B',
type=7)
24262 is a template id
the api return Error -32602: Invalid params., Incorrect API "create"

Create multiple hostgroups with one request

Hy,

please, imagine that easy example

hostgroups_to_create = ['foo', 'bar']
existing_hgs = api.hostgroup.get(filter={'name': hostgroups_to_create}) # works
if existing_hgs == []: # if hostgroups not defined, yet
    api.hostgroup.create(
        name=hostgroups_to_create
    ) # Error -32500: Application error.,

I tried a bunch of approaches to pass hostgroups variable content to name. (i.e. even such things: "'%s'" % "','".join(map(str, hostgroups_to_create))) But I just don't get it. It seems, only passing a string works, but I've only been able to create one hostgroup that way.
But this is not what I want, as I would like to have one request and one response. I'm new to python, so maybe I even missed a basic syntax?
However, the code examples didn't help. Could you please help me out?

Thanks
ITler

btw: I'm using zabbix 3

Create wrapper objects

Before I start to work on this I'd like your opinion on this. What I'd like to do is create objects to contain all data instead of dictionaries. In the first step they might even be as simple as named tuples, but in the end we could implement them to include save and delete functions (where save would look at the ID to determine whether it should create of update).

Update the PyZabbix Login Wiki

Hello Luke,

I'm using your wonderful library to do some tasks on Zabbix and I found a needed update for a wiki doc page:

https://github.com/lukecyca/pyzabbix/wiki

In my case, my zabbix is using the HTTP/Kerberos Auth, then I Need to use the customized Session token to login.

However, I cant login using just the information provided in the project's wiki page; the login method need to be called (at least in the Zabbix 2.0) with the user name.

For me, the following code is working like a charm:

https://dpaste.de/rcwp

In other words: if possible, just add the "zapi.login('USER',)" statement and the code will work.

Without this, just the following exception occurs:

Error -32602: Invalid params., Not authorized while sending[...]

The following thread at zabbix foruns pointed me to the way:

https://www.zabbix.com/forum/showthread.php?t=39103

Thank you!!!

Getting SSL error even with `zapi.session.verify=False`

I get the following traceback when trying to simply connect to our zabbix instances telling the session to verify=False.

If I try directly with requests (ie. no session) I have no issue.

This works:

r = requests.get('https://zabbix.server.com', verify=False, auth=('username', 'password'))

But if I remove verify=False I get the same error as below which is making me think the verify=False is not passing through the session for some reason?

Trying sessions natively through requests I also have no issue. This below is clean:

import requests

s = requests.Session()
s.auth=('username', 'password')
s.verify=False
r = s.get('https://zabbix.server.com/zabbix/api_jsonrpc.php')

The example I'm trying using pyzabbix that is failing is any of the samples on your readme.

Traceback (most recent call last):
  File "C:/projects/zabbix/scripts/query_api.py", line 31, in <module>
    zapi.login('svc_zabbix_api')
  File "C:\Python27\lib\site-packages\pyzabbix\__init__.py", line 70, in login
    self.auth = self.user.login(user=user, password=password)
  File "C:\Python27\lib\site-packages\pyzabbix\__init__.py", line 157, in fn
    args or kwargs
  File "C:\Python27\lib\site-packages\pyzabbix\__init__.py", line 103, in do_request
    timeout=self.timeout
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 508, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 465, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 573, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python27\lib\site-packages\requests\adapters.py", line 431, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

Error -32700 occurs when using pyzabbix

I'm running Python 2.7.5 on Centos 7 (build 7.0.01406), against Zabbix 2.2.1.
Traceback reads:

user@host ~/D/A/src> python main/zabbix/zab.py
Password:
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:730: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html (This warning will only appear once by default.)
  InsecureRequestWarning)
Traceback (most recent call last):
  File "main/zabbix/zab.py", line 79, in <module>
    trends()
  File "main/zabbix/zab.py", line 28, in trends
    limit="5000",)
  File "build/bdist.linux-x86_64/egg/pyzabbix/__init__.py", line 148, in fn

  File "build/bdist.linux-x86_64/egg/pyzabbix/__init__.py", line 125, in do_request

pyzabbix.ZabbixAPIException: ("Error -32700: Parse error, Invalid JSON. An error occurred on the server while parsing the JSON text. while sending {'params': {'output': 'extend', 'time_till': 1412013401.0, 'time_from': 1411999001.0, 'limit': '5000', 'itemids': ['item_id']}, 'jsonrpc': '2.0', 'method': 'history.get', 'auth': 'fbf781cf998b80ef1dfe28de02e1410e', 'id': 0}", -32700)

Oddly, I get this same 32700 error if I put some JSON calls to Zabbix API objects in a Bash script. Trying to figure out what to tell my Zabbix admin to check / change.

If I manually do a one-liner curl with json specified in a zabbixdata text file, such as

curl -k -H "Content-Type: application/json" --data @zabbixdata https://ourzabbixhost/api_jsonrpc.php

it works fine.

Have you or anyone else seen this problem?

confimport function throws zabbix errors

My situation:
zabbix 2.2.2 on an aws ubuntu 64 bit instance

I'm using pyzabbix to completely automate the set up and ongoing maintenance of a zabbix server. What I'm struggling with is the import of a template (previously exported through the zabbix front-end). Basically, I want to manually create a few templates - e.g. apache, mysql, linux os and export them to separate files. Then, using config mgmt and pyzabbix I'll import the templates.

I have tried using both xml, and json for import types. I can't seem to get an import to work using pyzabbix. As a test I also uploaded the exported templates using the front-end. That works without fail.

Here's how to repeat the issue:

  1. Using zabbix front-end do a full clone of a template. (e.g. template os linux)
  2. Prove that the export works by importing it - again using zabbix front-end.
  3. Use the confirmimport function to attempt to import the same exported template file. Observe the error thrown. (this requires some code to login first and etc.)
    Link to my gist of a class to do the import:

https://gist.github.com/wcannon/52e89070834c0d71a57f

e.g.
wcannon@wcannon-laptop:~/work/DevOps/monitoring$ ./test_config_import.py
Traceback (most recent call last):
File "./test_config_import.py", line 8, in
m.import_template("hpulse-linux.xml", "xml")
File "/home/wcannon/work/DevOps/monitoring/HpZabbix.py", line 33, in import_template
self.zapi.confimport(format=type, source=tempstr, rules=rules)
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/init.py", line 69, in confimport
params={"format": format, "source": source, "rules": rules}
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/init.py", line 117, in do_request
raise ZabbixAPIException(msg, response_json['error']['code'])
pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist! while sending {'params': {'rules': {'screens': {'createMissing': 'true'}, 'applications': {'createMissing': 'true'}, 'groups': {'createMissing': 'true'}, 'images': {'createMissing': 'true'}, 'templateScreens': {'createMissing': 'true'}, 'maps': {'createMissing': 'true'}, 'items': {'createMissing': 'true'}, 'triggers': {'createMissing': 'true'}, 'graphs': {'createMissing': 'true'}, 'hosts': {'createMissing': 'true'}, 'discoveryRules': {'createMissing': 'true'}}, 'source': '.....-----original xml of template exported goes here ----
followed by:
</zabbix_export>\n', 'format': 'xml'}, 'jsonrpc': '2.0', 'method': 'configuration.import', 'auth': u'0bd72bcbe8424c4432e272fe664d582c', 'id': 1}', -32500)

session timeout on do_request

There is no way to specify a timeout to the session used by the ZabbixAPI in the requests module.
so in the do_request method, if the session.post hangs and the server is not responding, the whole process is waiting.
Maybe we want to be able to specify a timeout?

MissingSchema exception

I am trying following example from Github tutorial.

from pyzabbix import ZabbixAPI

zapi = ZabbixAPI("localhost")
zapi.login("admin", "zabbix")
print "Connected to Zabbix API Version %s" % zapi.api_version()

for h in zapi.host.get(output="extend"):
print h['hostid']

I have Ubuntu 15 system on which zabbix-server is running. I am executing above example on same system. I get the following:

Traceback (most recent call last):
File "pyzabbixdemo.py", line 4, in
zapi.login("admin", "zabbix")
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/pyzabbix/init.py", line 68, in login
self.auth = self.user.login(user=user, password=password)
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/pyzabbix/init.py", line 156, in fn
args or kwargs
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/pyzabbix/init.py", line 101, in do_request
timeout=self.timeout
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/requests/sessions.py", line 508, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/requests/sessions.py", line 451, in request
prep = self.prepare_request(req)
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/requests/sessions.py", line 382, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/requests/models.py", line 304, in prepare
self.prepare_url(url, params)
File "/home/seagate/Documents/pyzabbix/pyzabbixdemo/local/lib/python2.7/site-packages/requests/models.py", line 362, in prepare_url
to_native_string(url, 'utf8')))
requests.exceptions.MissingSchema: Invalid URL 'localhost/api_jsonrpc.php': No schema supplied. Perhaps you meant http://localhost/api_jsonrpc.php?

Can anyone tell me what is wrong here because as a beginner I am not able to figure out ?

Publish pyzabbix on pypi

It would be useful if pyzabbix was available on pypi so we could depend on it in our project. This would also ned proper versioning by tagging then.

Login Failed & unicode error

{u'jsonrpc': u'2.0', u'id': 0, u'error': {u'message': u'\u65e0\u6548\u7684\u53c2\u6570.', u'code': -32602, u'data': u'\u767b\u5165\u540d\u79f0\u6216\u5bc6\u7801\u662f\u4e0d\u6b63\u786e\u7684.'}}
pyzabbix.pyc in do_request(self, method, params)
      130                 message=response_json['error']['message'],
      131                 data=response_json['error']['data'],
--> 132                  json=str(request_json)
      133                )
      134        raise ZabbixAPIException(msg, response_json['error']['code'])

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

configuration.import clashes with Python's import reserved keyword

Hi,
trying to use configuration.import yelds the following error:

zh.configuration.import(...)
                      ^

SyntaxError: invalid syntax

I worked around it by defining the following function inside the ZabbixAPI class and calling it instead of the canonical one:

def confimport(self, format='', source='', rules=''):
return self.do_request(method="configuration.import", params={"format": format, "source": source, "rules": rules})['result']

requests returning no data

Howdy,

I am using Zabbix v2.4.5. And I'm running into an issue where any requests that send parameters return no data.

Running the zapi.api_version() function gives me the proper version from the zabbix server. However, when I try 'zapi.hosts.get(output="extend")' I get no data back.

In the troubleshooting that I have done i found the following;

  • I am getting JSON data back from the zabbix server. the important part shows ..."result":[]...
  • There are hosts in the server.
  • If I run the same query manually I do get responses. I noticed that all of the query's listed in the zabbix API manual shows "JSON":"2.0" being one of the first things that is sent. However, the strings pyZabbix is sending start with the params and then send "JSON" at the very end. That's really the only difference I can see between the query's
  • The authentication function works fine - zabbix server sends back the right response
  • the api_version function works fine
  • if i intentionally mess up the command (zapt.hostt.get....) it will return an error message.

If you would like specific examples - or if there is anything I am messing up or can try please let me know.

Thanks for all your work on this!

Steve Reed

support for version 2.2

I tested the module with 2.2, and got result below

In [7]: zapi.hostgroup.get(extendoutput=True, sortfield='name')
Out[7]: 
[{u'groupid': u'5'},
 {u'groupid': u'7'},
 {u'groupid': u'2'},
 {u'groupid': u'1'},
 {u'groupid': u'8'},
 {u'groupid': u'6'},
 {u'groupid': u'4'}]

In [8]: zapi.host.get(extendoutput=True, sortfield='name')
Out[8]: [{u'hostid': u'10112'}, {u'hostid': u'10084'}]

there is no detailed infomation as the raw json-rpc, do you have plan support 2.2?

Add an option to ignore ssl validation errors

I've got this traceback when tried to connect to zabbix server via https with self-signed certificate:

  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/pyzabbix/__init__.py", line 70, in login
    self.auth = self.user.login(user=user, password=password)
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/pyzabbix/__init__.py", line 157, in fn
    args or kwargs
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/pyzabbix/__init__.py", line 103, in do_request
    timeout=self.timeout
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/requests/sessions.py", line 511, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/Users/olfway/Library/Python/3.5/lib/python/site-packages/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)

To disable verification, i had to modify source file and add verify=False to self.session.post call.

Could you please provide an option to pass "verify" without source code modification?

.delete methods don't work

Doesn't work:
zapi.item.delete( [12345] )
zapi.item.delete( ["12345"] )
zapi.item.delete( "12345" )

I get the following error:
TypeError: fn() takes exactly 0 arguments (1 given)

Python version 2.6.6

Could you obfuscate the password during an incorrect sign in

I get the following response which clearly shows the used password:

pyzabbix.ZabbixAPIException: ("Error -32602: Invalid params., Login name or password is incorrect. while sending {'params': {'password': 'guest', 'user': 'guest'}, 'jsonrpc': '2.0', 'method': 'user.login', 'id': 0}", -32602)

Update examples with pyzabbix new version

Hi lukecyca, I have recently worked with a project which using your pyzabbix. But I'm working with old version of you.
I review new code for new versions but seemly its structure is different from old version.
So I don't know how to use it.
If you can add some examples show me how to apply pyzabbix new version, I'm really grateful..

it seems doesn't support utf8

hello , sorry bother you, but i got question want to ask. in few days , i work on vcenter minitor use project called py-vpoller which they use you pyzabbix package. when i import vcenter vm hosts to zabbix hosts use zabbix-vsphere-import tool (https://github.com/dnaeon/py-vpoller/tree/master/extra/zabbix/vsphere-import) , it return error

"""
File "build/bdist.linux-x86_64/egg/pyzabbix/init.py", line 154, in fn
File "build/bdist.linux-x86_64/egg/pyzabbix/init.py", line 129, in do_request
UnicodeEncodeError: 'ascii' codec can't encode characters in position 56-59: ordinal not in range(128)
"""

in zabbix-vsphere-import script , it pass hostname to pyzabbix,but my hostname have chinese character,so , i think maybe it doesn't support utf8.

trend_data.py example is wrong

I just noticed the "trend_data.py" example: it is not possible to get trend data using Zabbix API so this example is misleading, it should be renamed to "history_data" and show the differences between the different "history=x" options (int, float, string, ...).
I will fix it, this is just a reminder :-)

zapi.api_version() invalid params

print "Connected to Zabbix API Version %s" % zapi.api_version()
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/init.py", line 80, in api_version
return self.apiinfo.version()
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/init.py", line 153, in fn
args or kwargs
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/init.py", line 130, in do_request
raise ZabbixAPIException(msg, response_json['error']['code'])
pyzabbix.ZabbixAPIException: ('Error -32602: Invalid params., The "apiinfo.version" method must be called without the "auth" parameter. while sending {'params': {}, 'jsonrpc': '2.0', 'method': 'apiinfo.version', 'auth': u'782c3b11011afc8884934a6c371f150b', 'id': 31}', -32602)

Alert script helper

Would you be open to a subclass being proposed with the intent of providing some wrapper functions for devs writing alert scripts? I realize the below don't match perfectly, but would be kewl if there was some commonality.

Things like:
https://github.com/PagerDuty/pdagent-integrations/blob/master/bin/pd-zabbix#L44-L54
https://github.com/gregswift/zabbix-alertscript-maintenance/blob/master/scripts/zabbix-maintenance-mode#L18-L19
https://github.com/gregswift/zabbix-alertscript-maintenance/blob/master/scripts/zabbix-maintenance-mode#L21-L28

requests.exceptions.HTTPError: 504 error using trigger.get method

I was trying to use trigger.get method to get all trigger info, but returned 504 Gateway Timeout exception. It never happened before, when I tried to get all the single host trigger info by specifying the host name using filter keyword it worked well. I thought it resulted from the increasing amount of hosts which means large number of trigger it returned. I have about 1800 hosts so far. Any solutions to this problem? Thank you!

Sending Array to Zabbix API

Hi,

I'm playing around trigger.deletedependencies call and try to send array of triggerid but seems pyzabbix does not allow to do it in properly way.

Does not work

     hosts_tr = zapi.trigger.get(group=hostgroup, filter={'description': trigger_desc})
     # Short version of hosts_tr:  [{u'triggerid': u'24344'}, {u'triggerid': u'24352'}]
     zapi.trigger.deletedependencies(hosts_tr)

Output

Sending: {
    "params": [
        [
            {
                "triggerid": "24344"
            },
            {
                "triggerid": "24352"
            }
        ]
    ],
    "jsonrpc": "2.0",
    "method": "trigger.deletedependencies",
    "auth": "My auth here",
    "id": 71
}
Response Code: 200
Response Body: {
    "jsonrpc": "2.0",
    "result": {
        "triggerids": []
    },
    "id": 71
}

request_json was wrapped array in additional list so Zabbix did not give my ids :(

Works

     zapi.trigger.deletedependencies({u'triggerid': u'24344'}, {u'triggerid': u'24352'})

I guest it may affect any methods that waiting array of objects.

fix_host_ips.py fails, wrong dict_keys / parms

Hi,

i tryed the example fix_host_ips.py against zabbix 2.0.8 and it fails for some reasons:

  1. the extendoutput=True param is not correct, you need to use output=extend
  2. there is no dns / ip value in the host params, you need to use hostinterface, and then the host param is missing.

against which version do you tested these example?

regsards f0

set Request timeout

Hello,
if I'm not wrong, right now with pyzabbix is possible to set a "session" timeout (via session.timeout), but it's not possible to set a request timeout (as "timeout=x" parameter), this could be very useful in case Zabbix dashboard isn't responding and you don't want to wait forever.
For example, with Requests library you can call: session.post('url','data',timeout=5) to set a 5 second timeout for the request, which is different than session.timeout=5 which is the session (i.e. cookie) persistence.

Run tests on Python 3

We currently only test against python 2.6 and 2.7, but advertise support for python 3 in setup.py.

ZBX-3783, API call mis-constructed

Misconstruction of host.get command to submit an Array not a Object results in erroneous results

[Command]
{"params": [
{
"filter": {"host": ["019615"]}, "output": ["extended"]
}
]
, "jsonrpc": "2.0", "method": "host.get", "auth": "b9d8c3c7f0c08bdd2c20f1ddb023cb27", "id": 9}

[Response]
'{"jsonrpc":"2.0","result":[{"hostid":"10096"}],"id":9}'

Can't create web scenarios

I'm trying to use pyzabbix to push a list of web scenarios to Zabbix via the api. However, because creating a web scenario requires a nested JSON input to create both the web scenario and the web scenario steps simultaneously I cannot find a way to make it work with pyzabbix.
For example:
z.httptest.create(name='Google', hostid='10138', authentication='0', retries='1', steps= ['url=google.com, name=google, no=1'])
results in the following JSON query being sent to the server:

Sending: {
"params": {
"retries": "1",
"authentication": "0",
"name": "Google",
"hostid": "10138",
"steps": [
"url=google.com, name=google, no=1"
]
},
"auth": "****",
"jsonrpc": "2.0",
"id": 2,
"method": "httptest.create"
}

Trying to format a multiline query in correct JSON format and inserting it into the parameter doesn't work because it is parsed and converted by the Python interpreter as far as I can tell:

steps = """ {
"name": "google",
"url": "google.com",
"no": 1
}"""
`z.httptest.create(name='Google', hostid='10138', authentication='0', retries='1',
steps= [steps])'

Sending: {
"jsonrpc": "2.0",
"method": "httptest.create",
"params": {
"hostid": "10138",
"name": "Google",
"steps": [
" {\n "name": "google",\n "url": "google.com",\n "no": 1\n }"
],
"authentication": "0",
"retries": "1"
},
"auth": "*******",
"id": 2
}
Response Code: 200
Response Body: {
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32602,
"data": "Web scenario step name cannot be empty.",
"message": "Invalid params."
}
}

I'm very new to python and programming in general, and any help would be appreciated. Thank you.

Getting Hosts/Host Groups

I am attempting to retrieve my host groups and the hosts that are in them;however, host.get does not return a 'groupid' or 'groupids' parameter. Here's my code:

for host in zapi.host.get():
    print host['groupids']

and I receive a key error for output:
KeyError: 'groupids'

Retrieving host by groupids should work as per Zabbix Documentation.

How do I retrieve host groups and their associated hosts?

expandData is deprecated since zabbix 2.4

So current_issues.py has issues

triggers = zapi.trigger.get(only_true=1,
                            skipDependent=1,
                            monitored=1,
                            active=1,
                            output='extend',
                            expandDescription=1,
                            expandData='host',
                            )

Getting Hosts from multiple groups

I want to search for all hosts that are located in two specific groups.

When I search with

zapi.host.get(output="extend", groupids=[group1, group2])

I get all hosts that are linked to one group. This is a logical "or". I am searching for the logical "and".

Is there a solution?

Regards

For Zabbix 2.4 we got: "pyzabbix.ZabbixAPIException: ('Error -32602: Invalid params., The "user.login" method must be called without the "auth" parameter."

Hi.

Thank you for great tool, its very helpful and simple to use.

Just trying new version of Zabbix and get this error:

"pyzabbix.ZabbixAPIException: ('Error -32602: Invalid params., The "user.login" method must be called without the "auth" parameter."

Info from manual (https://www.zabbix.com/documentation/2.4/manual/api/reference/user/login):

user.login
This method is available to unauthenticated users and must be called without the auth parameter in the JSON-RPC request.

Can you tell if it will be fixed? Do you plan to update pyzabbix to run well with Zabbix 2.4 version?

Getting Multiple Values Wont Work

Hello,

I'm trying to get some history values, but I cant get values from more than one item id in the same request. In the zabbix api documentation of the history.get we have the following info:

itemids string/array Return only history from the given items.

But with the pyzabbix, when I try to get more than one itemid history value, i just get the LAST value provided in the itemsids list.

Example:
zapi.history.get(hostids=['13088'], itemids=['146503', '14504'], limit=1)

Result:
[{'clock': '1428588104', 'itemid': '146504', 'ns': '701674174', 'value': '1'}]

Is that behaviour ok?

Adding elements to a map (not an issue)

Hi Lukecyca,

Thanks for this API it's really helpful, I managed to lots of automated tasks with it. Right now I'm struggling with the sysmap class trying to add elements into it.

-- This works fine, I can update a map's name.
zapi.sysmap.update( { "sysmapid":"4", "name":"My LAN" } )

The update() method in the official Zabbix API supports adding elements through the "selements" properties, but in Pyzabbix, it seems that we have to do it through addElements.

-- The line below fails.
zapi.sysmap.addElements( { "sysmapid":"4", "elementid" : "10056", "elementtype":"0", "x":"10","y":"10" } )

This is the error message :
zabbix_api.ZabbixAPIException: ('Error -32602: Invalid params., [ CMap::addElements ] Map add elements failed while sending {"params": {"sysmapid": "4", "x": "10", "elementtype": "0", "y": "10", "elementid": "10056"}, "jsonrpc": "2.0", "method": "map.addElements", "auth": "a27b31e3dc07eed33482f433580a8a9f", "id": 1}', -32602)

I tried several other ways to express the addElements line. I probably mess with the arrays. Without any examples, it's pretty hard to get this right.

If you have a working example, that would great.

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.