Coder Social home page Coder Social logo

py-zabbix's Introduction

Build Status Coverage PyPi status PyPi version

Zabbix module for Python

Install

You can install Zabbix modules for Python with pip:

pip install py-zabbix

Official documentation for py-zabbix

Examples

ZabbixAPI

from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
zapi = ZabbixAPI(url='https://localhost/zabbix/', user='Admin', password='zabbix')

# Get all monitored hosts
result1 = zapi.host.get(monitored_hosts=1, output='extend')

# Get all disabled hosts
result2 = zapi.do_request('host.get',
                          {
                              'filter': {'status': 1},
                              'output': 'extend'
                          })

# Filter results
hostnames1 = [host['host'] for host in result1]
hostnames2 = [host['host'] for host in result2['result']]

# Logout from Zabbix
zapi.user.logout()

Or use 'with' statement to logout automatically:

from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
with ZabbixAPI(url='https://localhost/zabbix/', user='Admin', password='zabbix') as zapi:

    # Get all monitored hosts
    result1 = zapi.host.get(monitored_hosts=1, output='extend')

Enable logging:

import sys
import logging
from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
logger = logging.getLogger("pyzabbix")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)

zapi = ZabbixAPI(url='http://localhost', user='Admin', password='zabbix')

Note that passwords and auth tokens are hidden when raw messages are logged or raised in exceptions ( but not hidden if print() is used):

ZabbixAPI.login(Admin,********)
Call user.login method
urllib2.Request(http://localhost/api_jsonrpc.php, {"jsonrpc": "2.0", "method": "user.login", "params": {"user": "Admin", "password": "********"}, "id": "1"})
Response Body: {
    "jsonrpc": "2.0",
    "result": "********",
    "id": "1"
}

ZabbixSender

from pyzabbix import ZabbixMetric, ZabbixSender

# Send metrics to zabbix trapper
packet = [
  ZabbixMetric('hostname1', 'test[cpu_usage]', 2),
  ZabbixMetric('hostname1', 'test[system_status]', "OK"),
  ZabbixMetric('hostname1', 'test[disk_io]', '0.1'),
  ZabbixMetric('hostname1', 'test[cpu_usage]', 20, 1411598020),
]

result = ZabbixSender(use_config=True).send(packet)

py-zabbix's People

Contributors

adubkov avatar b4hand avatar battleroid avatar bhuisgen avatar blodone avatar cavaliercoder avatar faolisilva avatar fxpester avatar fxthomas avatar gescheit avatar gomex avatar jbskytap avatar maksim77 avatar natict avatar neogan74 avatar nijel avatar potchin avatar shapez avatar sven-hergenhahn-dmtech avatar tyonar avatar v-zhuravlev 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

py-zabbix's Issues

Error using py-zabbix with python 3

Hi,

thanks for your work on this very usefull API.
I'm porting some monitoring code from python 2 to python 3, and I get this error only when executing the script with python 3:

configparser.DuplicateOptionError: While reading from '<???>' [line 300]: option 'userparameter' in section 'root' already exists

My zabbix-agent.conf is fine as for zabbix-agent. I don't see any warning or error on his side. As a matter of fact, on line 300, appears the second "UserParameter" option on my config file.
The documentation says "there can be several UserParameter in the file" : https://www.zabbix.com/documentation/3.4/manual/appendix/config/zabbix_agentd

I could'nt find anything on the web about this problem, hence this issue post.

Thanks for your help !

Zabbix discovery

Hi,
Is there a way of using this module to send Zabbix discovery items?
Thanks.

Do_request method using filter has no effect

hi,
Example request:
result2 = zapi.do_request('graphitem.get', { 'filter': {'itemid': 22902}, })

filter doesn't work in the method.The result is the same as not using filter.
plz help me!ths

UserParameters in config

If you have multiple user parameters specified in config and use_config=True, you will get an error:

  File "/usr/local/lib/python3.5/dist-packages/pyzabbix/sender.py", line 192, in __init__                                                             [5/1893]
    self.zabbix_uri = self._load_from_config(use_config)
  File "/usr/local/lib/python3.5/dist-packages/pyzabbix/sender.py", line 246, in _load_from_config
    config.readfp(config_file_fp)
  File "/usr/lib/python3.5/configparser.py", line 760, in readfp
    self.read_file(fp, source=filename)
  File "/usr/lib/python3.5/configparser.py", line 715, in read_file
    self._read(f, source)
  File "/usr/lib/python3.5/configparser.py", line 1089, in _read
    fpname, lineno)
configparser.DuplicateOptionError: While reading from '<???>' [line 305]: option 'userparameter' in section 'root' already exists```

Namespace conflict

The "py-zabbix" library conflicts with "pyzabbix" library.

https://pypi.org/project/py-zabbix/
https://pypi.org/project/pyzabbix/

Both libraries writes into directory "pyzabbix" and effectively overwrites each other after pip install.

I have some code based on (other) "pyzabbix" library that does not support Zabbix Sender.
Now I need to add zabbix sender functionality but I do not wan to rewrite my old code for the new py-zabbix library, this is not currently possible.

The issue can be fixed by renaming the directory to "py-zabbix" as package name suggest.

Hostname autodetection

It would be a good idea to load an agent hostname from a config (Hostname=) the same way it happens with Server= and Port= options.
Right now I need to duplicate some config parsing, doing it the same way as py-zabbix:

config_file = '/etc/zabbix/zabbix_agentd.conf'
with open(config_file, 'r') as f:
    config_file_data = "[root]\n" + f.read()
config_file_fp = StringIO(config_file_data)
config = configparser.RawConfigParser()
config.readfp(config_file_fp)
agent_hostname = config.get('root', 'Hostname')

Why the double parse, when we could do it in one place, just like zabbix-sender? 🐒

"'bool' object has no attribute 'get'" error occurs in ZabbixSender.send() function

Hello,

I found a problem and will report it.

Perhaps the conditional statement in the ZabbixSender._chunk_send() function on line 425 of pyzabbix/sender.py may be incorrect.

if response and response.get('response') != 'success':

If False is returned from ZabbixSender._get_response() function on line 422 of pyzabbix/sender.py, exception handling may not be executed.

Probably the correct one is as follows.

if not response or response.get('response') != 'success':

Zabbix Sender add old data

Hi,

I'm trying to send to Zabbix old data with old timestamp, but Zabbix puts the data on the current position.

Eg:
Wednesday, 22 May 2019 16:55:00 - Epoch timestamp: 1558544100
Value = 50

Current date:
Wednesday, 22 May 2019 21:01:01 - Epoch timestamp: 1558558861

Code:
packet = [ ZabbixMetric('host1', 'test.key',50, 1558544100) ]

Wrong default timestamp in ZabbixMetric.

Now, if the time is not specified when creating an instance ZabbixMetric attribute will take the value str(int(time.time())).

But this is not right! The default behavior zabbix_sender (official utility I mean) implies that the server assumes its current time. No one can imagine how precisely set the time on the machine from which you run py-zabbix. This parameter should be determined server-side part!

get_id() not work with map object

zbx_api.get_id(item_type='map', item='Mymap')

print(zbx_api.get_id(item_type='map', item='Mymap'))

File "/py3-venv/lib/python3.4/site-packages/pyzabbix/api.py", line 333, in get_id
result.append(int(obj.get(item_id)))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Zabbix_sender reimplement

Hello,

I suggest reimplement command zabbix_sender by py-zabbix. This can be useful when monitoring a shared environment when you do not have the ability to install your own system packages, but can trigger the sender, for example, through cron.

Greetings,

ZabbixSender and UTF LLD

I'm trying to find proper way to send LLD JSON-data to Zabbix Server, but still without result.
If I use UTF-symbols in Macro's value, Zabbix Servers disables lld-item with "Value should be a JSON object" error. (I tried a lot of u"XXX", *.encode, *.decode combinations)
Does anybody have some ideas how to change next pease of code to make it works?

# -*- coding: utf-8 -*-
...
sys.setdefaultencoding('UTF8')
...
data = '{"data": [{"{#ID}": "28502", "{#DESCRIPTION}": "Й"}]}'
zm = ZabbixMetric(host, zkey, data)
result = ZabbixSender(nocs).send([zm])

getting error when sending data to zabbix server

I am testing a code snippet

                from pyzabbix import ZabbixMetric, ZabbixSender, ZabbixResponse
                metrics= [ZabbixMetric('mme01', 'TEST', '20')]
                ZabbixSender('10.46.224.5').send(metrics)

When I run this I get an error -

Traceback (most recent call last):
File "zabbix_sender.py", line 14, in
ZabbixSender('10.46.224.5').send(metrics)
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/sender.py", line 433, in send
result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
File "/usr/local/lib/python2.7/dist-packages/pyzabbix/sender.py", line 408, in _chunk_send
logger.warn('Sending failed: %s', err.msg)
AttributeError: 'error' object has no attribute 'msg'

What am I missing ? How can diagnose the issue. I have connectivity to the IP "10.46.224.5" from my linux box.

TLS PSK usage with ZabbixSender

I've spent quite a lot of time trying to set up a TLS connection with PSK. I finally managed to do that, so I thought I'd share my solution in hope that it would save someone time.

The python ssl package doesn't provide support for PSK, it supports just the certificates. But there's a nice little package which does provide support for TLS PSK: https://github.com/drbild/sslpsk

The tricks are:

  • sslpsk expects that its wrap_socket would be called after socket.connect(...), while the ssl.wrap_socket expects that it would be called before socket.connect(...).
  • Zabbix server seems to accept only a single TLS cipher, which the client might not announce (I guess because it is a weak one).

So here is a solution that works for me with Zabbix server 4.2:

import functools
import ssl

import sslpsk
from pyzabbix import ZabbixMetric, ZabbixSender


class PyZabbixPSKSocketWrapper:
    """Implements ssl.wrap_socket with PSK instead of certificates.

    Proxies calls to a `socket` instance.
    """

    def __init__(self, sock, *, identity, psk):
        self.__sock = sock
        self.__identity = identity
        self.__psk = psk

    def connect(self, *args, **kwargs):
        # `sslpsk.wrap_socket` must be called *after* socket.connect,
        # while the `ssl.wrap_socket` must be called *before* socket.connect.
        self.__sock.connect(*args, **kwargs)

        # `sslv3 alert bad record mac` exception means incorrect PSK
        self.__sock = sslpsk.wrap_socket(
            self.__sock,
            # https://github.com/zabbix/zabbix/blob/f0a1ad397e5653238638cd1a65a25ff78c6809bb/src/libs/zbxcrypto/tls.c#L3231
            ssl_version=ssl.PROTOCOL_TLSv1_2,
            # https://github.com/zabbix/zabbix/blob/f0a1ad397e5653238638cd1a65a25ff78c6809bb/src/libs/zbxcrypto/tls.c#L3179
            ciphers="PSK-AES128-CBC-SHA",
            psk=(self.__psk, self.__identity),
        )

    def __getattr__(self, name):
        return getattr(self.__sock, name)


sender = ZabbixSender(
    zabbix_server="my.zabbix.host",
    socket_wrapper=functools.partial(
        PyZabbixPSKSocketWrapper,
        identity="PSK myidentity",  # your PSK identity
        psk=bytes.fromhex(
            "0cd204cf169ade0bbdcd13c95594eadd008eed1b4411856b6e16e10ee6b69458"  # your PSK
        ),
    ),
)

It would be nice if ZabbixSender(use_config=True) could automatically detect PSK settings from the config and use them, but I guess this solution might seem to be a bit hacky to be included to the package. Especially given that the sslpsk package on pypi does not provide manylinux/macos wheels and needs openssl headers and gcc to be present on the system to be installed.

I would be glad to know if there's a cleaner way to achieve the TLS PSK support with this package.

Python3 compatibility

ConfigParse change in python3 and StringIO is not a module anymore.

#15

But still have error of compatibility:

File "/usr/local/lib/python3.4/dist-packages/zabbix/sender.py", line 221, in send
packet = self.__create_packet(request)
File "/usr/local/lib/python3.4/dist-packages/zabbix/sender.py", line 170, in __create_packet
packet = 'ZBXD\x01' + data_len + request
TypeError: Can't convert 'bytes' object to str implicitly

Cert-based TLS support

Does this module (esp. sender part) support cert-based encryption?
If yes - how to use it?

Release 1.1.5 and git regression

There is some problems about the git management on this project & the pypi packages releases.

I did the PR #119 merged for the release 1.1.5 so there was the git branch "release-1.1.5". But the next PR merge on this branch reintroduces old code and revert my fixes.

In addition to that if you check your pypi package 1.1.5, its content doesn't fit the version from the release branch (check this file: https://github.com/adubkov/py-zabbix/blob/release-1.1.5/pyzabbix/sender.py). It seems that the pip content was from the master branch.

I can of course recreate a new PR but please be careful. Right now I have the same reconnection problem as the previous release: my agents stopped to send metrics as the server has been simply upgraded. A generic exception is raised from code (which is bad) and it has ended all my sending threads:

2019-09-25T11:16:18.765877380Z zabbix-agent.0.7asa483dbvnx@node    | Exception in thread Thread-30:
2019-09-25T11:16:18.765880649Z zabbix-agent.0.7asa483dbvnx@node    | Traceback (most recent call last):
2019-09-25T11:16:18.765885963Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 398, in _chunk_send
2019-09-25T11:16:18.765891031Z zabbix-agent.0.7asa483dbvnx@node    |     connection.connect(host_addr)
2019-09-25T11:16:18.765916043Z zabbix-agent.0.7asa483dbvnx@node    | ConnectionRefusedError: [Errno 111] Connection refused
2019-09-25T11:16:18.765920133Z zabbix-agent.0.7asa483dbvnx@node    |
2019-09-25T11:16:18.765923246Z zabbix-agent.0.7asa483dbvnx@node    | During handling of the above exception, another exception occurred:
2019-09-25T11:16:18.765927220Z zabbix-agent.0.7asa483dbvnx@node    |
2019-09-25T11:16:18.765930393Z zabbix-agent.0.7asa483dbvnx@node    | Traceback (most recent call last):
2019-09-25T11:16:18.765933610Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/threading.py", line 917, in _bootstrap_inner
2019-09-25T11:16:18.765937051Z zabbix-agent.0.7asa483dbvnx@node    |     self.run()
2019-09-25T11:16:18.765940130Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/zabbixdocker/services/swarm.py", line 853, in run
2019-09-25T11:16:18.765943553Z zabbix-agent.0.7asa483dbvnx@node    |     self._zabbix_sender.send(metrics)
2019-09-25T11:16:18.765946790Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 433, in send
2019-09-25T11:16:18.765950395Z zabbix-agent.0.7asa483dbvnx@node    |     result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
2019-09-25T11:16:18.765953576Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 408, in _chunk_send
2019-09-25T11:16:18.765957177Z zabbix-agent.0.7asa483dbvnx@node    |     logger.warn('Sending failed: %s', err.msg)
2019-09-25T11:16:18.765960403Z zabbix-agent.0.7asa483dbvnx@node    | AttributeError: 'ConnectionRefusedError' object has no attribute 'msg'
2019-09-25T11:16:18.765963584Z zabbix-agent.0.7asa483dbvnx@node    |
2019-09-25T11:16:18.765966748Z zabbix-agent.0.7asa483dbvnx@node    | Exception in thread Thread-24:
2019-09-25T11:16:18.765970058Z zabbix-agent.0.7asa483dbvnx@node    | Traceback (most recent call last):
2019-09-25T11:16:18.765973741Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 398, in _chunk_send
2019-09-25T11:16:18.765977092Z zabbix-agent.0.7asa483dbvnx@node    |     connection.connect(host_addr)
2019-09-25T11:16:18.765984206Z zabbix-agent.0.7asa483dbvnx@node    | ConnectionRefusedError: [Errno 111] Connection refused
2019-09-25T11:16:18.765987654Z zabbix-agent.0.7asa483dbvnx@node    |
2019-09-25T11:16:18.765990835Z zabbix-agent.0.7asa483dbvnx@node    | During handling of the above exception, another exception occurred:
2019-09-25T11:16:18.765994195Z zabbix-agent.0.7asa483dbvnx@node    |
2019-09-25T11:16:18.765997351Z zabbix-agent.0.7asa483dbvnx@node    | Traceback (most recent call last):
2019-09-25T11:16:18.766000694Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/threading.py", line 917, in _bootstrap_inner
2019-09-25T11:16:18.766004908Z zabbix-agent.0.7asa483dbvnx@node    |     self.run()
2019-09-25T11:16:18.766008172Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/zabbixdocker/services/volumes.py", line 115, in run
2019-09-25T11:16:18.766011977Z zabbix-agent.0.7asa483dbvnx@node    |     self._zabbix_sender.send(metrics)
2019-09-25T11:16:18.766015270Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 433, in send
2019-09-25T11:16:18.766018585Z zabbix-agent.0.7asa483dbvnx@node    |     result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
2019-09-25T11:16:18.766021876Z zabbix-agent.0.7asa483dbvnx@node    |   File "/opt/python/lib/python3.7/site-packages/pyzabbix/sender.py", line 408, in _chunk_send
2019-09-25T11:16:18.766025290Z zabbix-agent.0.7asa483dbvnx@node    |     logger.warn('Sending failed: %s', err.msg)
2019-09-25T11:16:18.766028554Z zabbix-agent.0.7asa483dbvnx@node    | AttributeError: 'ConnectionRefusedError' object has no attribute 'msg'
2019-09-26T00:28:41.752618106Z zabbix-agent.0.7asa483dbvnx@node    |     39:20190926:002841.751 Executing command 'HOME=/var/lib/zabbix /usr/bin/puppet agent --version'

My code which excepts OSError exceptions: https://github.com/bhuisgen/zabbix-docker/blob/4df90647400b8f3e681bbd82d724a02aea8b69ed/zabbixdocker/services/containers.py#L196

My "previous" fix for py-zabbix : e1f80e4

Low Level discover

Is this possible to use py-zabbix with Low Level Discover ? I did not see any example of dynamic item creation. I was able to update status of an already created item using zabbix_sender.

Include ignored on zabbix_agentd.conf when using use_config

Hello,

I'm starting to use this module and finaly I made it work, but I've noticed that use_config options seems to be ignoring the includes of config file.

I've the config file with the default options (I preffer to leave it). Then I have a custon config inside /etc/zabbix/zabbix_agentd.d folder that replace those default options, and is working fine on the zabbix agent and also on zabbix_sender command.
One of those options is the zabbix server, and I'm thinking that are no being loaded, because I'm getting this error trying to send data with use_config=True:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/pyzabbix/sender.py", line 398, in _chunk_send
    connection.connect(host_addr)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./get_memory.py", line 167, in <module>
    sender.send(packet)
  File "/usr/local/lib/python3.5/dist-packages/pyzabbix/sender.py", line 433, in send
    result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
  File "/usr/local/lib/python3.5/dist-packages/pyzabbix/sender.py", line 408, in _chunk_send
    logger.warn('Sending failed: %s', err.msg)
AttributeError: 'ConnectionRefusedError' object has no attribute 'msg'

I was trying to figure out what was the problem until I've decided to use the host IP instead that option, and then has worked perfectly. After looking into the code to see if maybe I did something wrong, I've seen that looks like the problem is the configparser library, because looks like is not able to manage the imports (or at least I was not able to found a way beyond the manual import of every file).

Is there any way to manage this?.
I know that just setting the file where the serverIP is located works, but I preffer something more generic, to avoid problems later because the "out of default" customizations.

Best regards.

Provide a timeout parameter for socket.connect()

Please, provide a timeout parameter for send(), because if the server (or proxy) is not running the script was stucked.

The problem is the socket.connect() doesn't send the (optional) timeout parameter.

Cannot login to Zabbix with HTTP Authentication

Hi,

i'm trying to use py-zabbix library to do some task but i cannot login.
I configure my Zabbix Frontend to use "HTTP Authentication" for login.

When i use:
zapi = ZabbixAPI(url='https://zabbixserver.xxx.com/zabbix', user='zbxuser', password='zbxpassword' )
i receive a "401 Unauthorized".

Other library, like https://github.com/lukecyca/pyzabbix, manage correctly the session while logging into a Zabbix that use HTTP Auth.
Can you please implement "session management" also on this library?

Thx a lot in advance,

Andrea

ImportError: No module named configparser

I installed py-zabbix with pip.
What i'm doing wrong ?

root@host1:/tmp# pip --version
pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)
root@host1:/tmp# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from zabbix.sender import ZabbixMetric
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/zabbix/sender.py", line 1, in <module>
    import configparser
ImportError: No module named configparser
>>>

Zabbix 6.0 support

I was wondering is there a plan to add support for Zabbix 6.X to the module i just upgraded my environment and was doing some tests with the SLA services and its not working most likely because of the Service api redesign

感人

这里和博客里写的使用手册
简洁精炼
真tm感人

Why always recieve {"failed": 1, "chunk": 1, "total": 1, "processed": 0, "time": "0.000045"},Pls help on this

[root@centos ~]# yum install zabbix-sender
[root@centos ~]# zabbix_sender -s "consul1" -z 127.0.0.1 -p 10051 -k "mongodb_conn" -o 1
Response from "127.0.0.1:10051": "processed: 1; failed: 0; total: 1; seconds spent: 0.000250"
sent: 1; skipped: 0; total: 1

no data
mongodb- zabbix -templates-4.0 /mongod-db.py

ZBSERVER = 'localhost'
ZBPORT = 10051
packet = []
packet.append(ZabbixMetric(zbhost, "mongodb_conn", conn))
result = ZabbixSender(zabbix_server = ZBSERVER, zabbix_port = ZBPORT).send(packet)
print(result)  // {"failed": 1, "chunk": 1, "total": 1, "processed": 0, "time": "0.000045"}
print(packet) //  [{"host": "consul1 ", "value": "8", "key": "mongodb_conn"}]
  • Zabbix 4.2

py-zabbix and pyzabbix conflict

Why both of your modules use the same pip install folders? I have server with several running scripts. Some of the scripts use pyzabbix module, and another ones py-zabbix module (scripts from the internet, I don't have time to review every one of them). And one bunch of them is always not working because of using the same name from another module.

Modules installation paths:
py-zabbix (https://github.com/adubkov/py-zabbix)
/usr/local/lib/python3.8/dist-packages/py_zabbix-1.1.7.dist-info/*
/usr/local/lib/python3.8/dist-packages/pyzabbix/*
/usr/local/lib/python3.8/dist-packages/zabbix/*
pyzabbix (https://github.com/lukecyca/pyzabbix)
/usr/local/lib/python3.8/dist-packages/pyzabbix-1.0.0.dist-info/*
/usr/local/lib/python3.8/dist-packages/pyzabbix/*

I was able to fix it by installing pyzabbix, renaming its folder to pyzabbix2 and uninstalling and then installing py-zabbix and using "from pyzabbix2 import ZabbixAPI" for the first module
But this is fundamentally wrong!
Maybe you should somehow cooperate and use you own names/folders to avoid such conflicts?

How use py-zabbix with parameters: filter, search

The manual is no information.
Example request:
{
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": "10084",
"search": {
"key_": "system"
},
"sortfield": "name"
},
"auth": "038e1d7b1735c6a5436ee9eae095879e",
"id": 1
}

Request:
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {
"host": [
"Zabbix server",
"Linux server"
]
}
},
"auth": "038e1d7b1735c6a5436ee9eae095879e",
"id": 1
}

Sender send incorrect value in the utf8 encoding

Check in Python 2/3


if __name__ == "__main__":

    metrics = []

    zbx = ZabbixSender(SENDERURL)

    m = ZabbixMetric('test_rus', 'test_rus_key', 'Тест')

    metrics.append(m)

    zbx.send(metrics)

In a zabbix:

image

How can I solve this problem?

does it work with zabbix 3.2?

Hello! i have zabbix 3.2 and one strange problem
#!/usr/bin/python3 from pyzabbix import ZabbixAPI import sys zabbix_server='http://localhost/zabbix' z = ZabbixAPI(zabbix_server) z.login('userhere','passhere') #z = ZabbixAPI('http://localhost/zabbix', user='kulikov',password='Dtctkjvjybnjhbv@2017') #get host name as parameter (it must be caught up from trigger) host_name=sys.argv[1] #template we add templateadd_name = 'Adaptec RAIDs SNMP_maxview_copy' #template we delete templatedel_name = 'test_raid_software' #get host_id hostinfo = z.host.get(filter={"host": host_name}, output="hostid") templateaddinfo = z.template.get(filter={"host": templateadd_name}, output="templateid") templatedelinfo = z.template.get(filter={"host": templatedel_name}, output="templateid") if hostinfo: host_id=hostinfo[0]["hostid"] #get template id for add templateadd_id=templateaddinfo[0]["templateid"] #get template id for delete (now we don't need template for checking software) templatedel_id=templatedelinfo[0]["templateid"] try: z.host.massadd(hosts={"hostid":host_id},templates={"templateid":templateadd_id},templates_clear={"templateid":templatedel_id}) #z.host.massadd(hosts={"hostid":host_id},templates_clear={"templateid":templatedel_id}) except ZabbixAPIException as e: print(e) sys.exit() else: print("No hosts found")
This script is working not any time and doesn't delete template

Zabbix 3.0.1. The "apiinfo.version" method must be called without the "auth" parameter.

Hi
python 3.4.3
Zabbix 3.0.1
Install py-zabbix from pypi.

from pyzabbix import ZabbixAPI
zbx_api = ZabbixAPI(url='https://zabbix.example.ru', use_authenticate=False, user='admin', password='admin')
zbx_api.api_version()

File "test.py", line 15, in main
zbx_api.api_version()
File "/pyzabbix/api.py", line 162, in api_version
return self.apiinfo.version()
File "/pyzabbix/api.py", line 82, in fn
args or kwargs
File "/pyzabbix/api.py", line 229, in do_request
raise ZabbixAPIException(msg, err['code'])
pyzabbix.api.ZabbixAPIException: ('Error -32602: Invalid params., The "apiinfo.version" method must be called without the "auth" parameter. while sending {'params': {}, 'auth': 'f1c7dce7a38cd8055a07da18ef6d5671', 'jsonrpc': '2.0', 'method': 'apiinfo.version', 'id': '1'}', -32602)

support to new auth token

as zabbix 5.4 introduced support for auth token, is planned to integrate this feature in this python module ?

Zabbix exception on auth attempt

Receive following error when attempting to auth against Zabbix with username + password:

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

Seems like the login request uses the same do_request method as all other requests, which include this auth parameter. This is invalid in user.login requests, at least with Zabbix 2.4.1

Autodetection of servers is wrong

The code that determines which server to send a metric to (_load_from_config) queries the "Server" and "Port" sections of the zabbix config. It should query the "ServerActive" parameter, in fact the "Port" parameter is not valid and zabbix will not start if its present...

Starting Zabbix agent: zabbix_agentd [21739]: unknown parameter [Port] in config file [/etc/zabbix/zabbix_agentd.conf], line 88

From the config..

Option: ServerActive
List of comma delimited IP:port (or hostname:port) pairs of Zabbix servers for active checks.
If port is not specified, default port is used.
IPv6 addresses must be enclosed in square brackets if port for that host is specified.
If port is not specified, square brackets for IPv6 addresses are optional.
If this parameter is not specified, active checks are disabled.
Example: ServerActive=127.0.0.1:20051,zabbix.domain,[::1]:30051,::1,[12fc::1]

If hostname is not specified in metric system hostname should be used.

It's good idea to automatically use system hostname if it's not specified in ZabbixMetric.
Only parameters we really need is key and value.
The weird thing is, we can't just change ZabbixMetric class because it's already widely used. Perhaps we should create another Metric class for that.

Connection error

Hi,
I am sorry to bother you with that, but since we upgraded our zabbix (zabbix 3 to 3.2), we got the following error :

Error connection Zabbix :("Error -32700: Parse error, Invalid JSON. An error occurred on the server while parsing the JSON text. while sending {'params': {'password': 'MyPASS', 'user': 'MyUserZabbixAPI'}, 'jsonrpc': '2.0', 'method': 'user.login', 'id': '1'}", -32700)

Function :

def pyzabbix(alarme,valeur):
try:
# Create ZabbixAPI class instance
zapi = ZabbixAPI(url='https://My-zabbix.server/', user='MyUserZabbixAPI', password='MyPASS')
zapi.api_version()
print zapi
# Send metrics to zabbix trapper
packet = [
ZabbixMetric('MyHost', alarme, valeur)
]
result = ZabbixSender(use_config=True).send(packet)
print result
except Exception as e:
print "Error connection Zabbix :" + str(e)

Do you have an idea ?

Thank you ! 👍

not possible to insert via zabbix send

with an easy script it is not possible to update the key on the given hostname:

from  pyzabbix import ZabbixMetric, ZabbixSender
metrics = []

m = ZabbixMetric('paradox.states.system.power', 'battery', 10)
metrics.append(m)
pprint(metrics)

server = ZabbixSender('192.168.1.1','10051')
result = server.send(metrics)

with this given result:
python3 battery.py
[{"host": "paradox.states.system.power", "key": "battery", "value": "10"}]
Traceback (most recent call last):
File "battery.py", line 13, in
result = server.send(metrics)
File "/usr/local/lib/python3.6/dist-packages/pyzabbix/sender.py", line 443, in send
result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
File "/usr/local/lib/python3.6/dist-packages/pyzabbix/sender.py", line 408, in _chunk_send
connection.connect(host_addr)
TypeError: an integer is required (got type str)

what can i do?

Receive the response header is not correct.

In the process of writing tests for the module have stumbled upon strange behavior __receive in class ZabbixSender.
If the server did not respond immediately that is socket.recv returned False then exits the waiting loop.Thus response_header will be equal to b".
Here's a test which I tested this feature:

from unittest import TestCase
from unittest.mock import patch, call
from zabbix.sender import ZabbixSender

class TestsZabbixSender(TestCase):
    @patch('zabbix.sender.socket.socket', autospec=True)
    def test_zs_recive(self, mock_socket):
        mock_data = b'\x01\\\x00\x00\x00\x00\x00\x00\x00'
        mock_socket.recv.side_effect = (False, b'ZBXD', mock_data)
        zs = ZabbixSender()
        result = zs._ZabbixSender__receive(mock_socket, 13)
        self.assertEqual(result, b'ZBXD' + mock_data)
        self.assertEqual(mock_socket.recv.call_count, 3)
        mock_socket.recv.assert_has_calls([call(13), call(13), call(9)])

To wait for an answer was correct should probably change the _receive method something like this:

@classmethod
def __receive(cls, sock, count):
    """
    Reads socket to receive data from zabbix server.

    Attributes:
      socket (socket):  Socket object from which data should be read
      count (int):  Amount of data that should be read from socket, in bytes.
    """

    buf = b''

    while len(buf) < count:
        chunk = sock.recv(count - len(buf))
        if not chunk:
            pass
        else:
            buf += chunk

    return buf

Although the waiting becomes eternal. May be worth adding some counter iteracy or time?

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.