Giter VIP home page Giter VIP logo

check-mk-web-api's Introduction

check-mk-web-api Build Status

supported Checkmk versions

  • 1.6.0
  • 1.5.0

Installation

  • From source code
git clone https://github.com/brennerm/check-mk-web-api
cd check-mk-web-api
sudo python setup.py install
  • With pip
pip install check_mk_web_api

Quickstart

Initialization

import check_mk_web_api
api = check_mk_web_api.WebApi('http://checkmk.company.com/check_mk/webapi.py', username='automation', secret='123456')

Add Host

>>> api.add_host('webserver00.com')

Add Host in an existing WATO folder

>>> api.add_host('webserver00.com', folder='webservers')

Note there is no leading '/' on the folder name.

Edit Host

>>> api.edit_host('webserver00.com', ipaddress='192.168.0.100')

Delete Host

>>> api.delete_host('webserver00.com')

Delete Hosts

>>> api.delete_hosts(['webserver00.com', 'webserver01.com' ])

Get Host

>>> api.get_host('webserver00.com')
{
    'hostname': 'webserver00.com',
    'attributes': {
        'ipaddress': '192.168.0.100'
    },
    'path': ''
}

Get All Hosts

>>> api.get_all_hosts()
{
    'webserver00.com': {
        'hostname': 'webserver00.com',
        'attributes': {
            'ipaddress': '192.168.0.100'
        },
        'path': ''
    },
    'webserver01.com': {
        'hostname': 'webserver01.com',
        'attributes': {
            'ipaddress': '192.168.0.101'
        },
        'path': ''
    }
}

Discover Services

>>> api.discover_services('webserver00.com')
{'removed': '0', 'new_count': '16', 'added': '16', 'kept': '0'}

Bake Agents

>>> api.bake_agents()

Activate Changes

>>> api.activate_changes()

check-mk-web-api's People

Contributors

brennerm avatar cboseck avatar florianheigl avatar jongeneel avatar kgroshert avatar perlduck avatar philipplemke avatar ravibhure avatar yogibaer75 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

Watchers

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

check-mk-web-api's Issues

add host attributes

Hey,

how i can add custom host attributes?

{'hostname': 'myserver123',
 'folder': '',
 'attributes': {'ipaddress': '192.168.0.42',
                'site': 'mysite',
                'parent': 'server01'
                'tag_agaent': 'cmk-agent'}}

greetings
sam

add wiki doc on how to manually add a new hosttag [ or add a add_hosttags() ] function

I am not a python programmer, ( which is why I choose to use a api middleware ) could you please consider either documenting how one would use the get_hosttags() and subsequent set_hosttags() functions step by step for adding a new hosttag using python?

Would be even nicer if the check-mk-web-api could even do this all internally and expose a simple add_hosttags() function.

Thanks for any hints and help in this direction.

editing hosts

Hi ;-)

So, one thing I had postponed a month back and just returned to:

  • When I add a host, I can pass tags or a WATO folder.
  • When I try to do an update, I get an error

Check_MK Fehler: Unbekanntes Attribut: tags

(same with folder)

I can imagine API-side issues updating folders (would love none though) but since I can't do even tags, it feels strange.

I've tried for a bit, sending back the same structure as one receives on get_host using update_host seems to not be possible.
Do you have any advice about modifying what's in the attributes dictionary of the API query?

My use case is manyfold, first I store a hash of the system's host tags and other stuff in the alias field, then I compare that value to see if any system has been updated in CMDB etc.
If yes, I want to apply the updates to the existing host.

For now I think I can work around by deleting the node, but if you got an example updating more than the ip I would be very curious.

the output of get_hosttags() is NOT valid JSON

the output of get_hosttags() look much more like python(str) format to me, with the value key pairs being quoted in single quotes.

But valid JSON only has double quotes.

How do I get the check-mk-web-api calls to return or display valid JSON with double quotes? Sorry if I am missing the forrest for the trees here.

Support for python 2.7 ?

Awesome! We ended up developing our own before we even realized the checkmk webapi existed. It's a large amount of logic designed to reproduce the WATO UI calls. We'd love to eventually migrate to the webapi using this webapi library wrapper rather than rolling our own.

To the sad part... My corporate environment hasn't upgraded to python3. Would you be opposed to adding support for python2.7? Things like the type hints break python2.7 compatibility. There may be others too; this is just the first error encountered.

If you're cool with this, I'm happy to fork and contribute back.

PS - python2.7 supports type hints comments in some tools like pycharm

New release with fixes in `master`

Hi @brennerm,

Awesome project! Thanks so much, we are adding auto registering new hosts into our CheckMK monitoring this morning and your package saved a ton of time! ๐Ÿ‘

I had a quick question, when will you be releasing the new release (ie 1.4 is out at time of this post and in PyPi so asking about 1.5). Specifically, lost some time this morning on the fix in this commit: ebd68c5. Would help with installs from pip versus needing to install from source right now off of master with set commit.

Again, really appreciate your work! Thanks!

Best,
Marshall

set_hosttags failed to parse JSON request with special character &

We have taggroup-titles with special characters like &.

  • api.get_hosttags() โœ”๏ธ (works)
  • api.set_hosttags(tags) โŒ (fails)

Within the tags-dictionary there is a taggroup with "title": "Mail & Ansicht"

Exception:
check_mk_web_api.exception.CheckMkWebApiException: Check_MK exception: Failed to parse JSON request: '{"tag_groups": [{"topi ... {"title": "Mail ': Unterminated string starting at: line 1 column 1778 (char 1777)

Workaround in check_mk_web_api/__init__.py:

@staticmethod
    def __build_request_data(data, request_format):
        ...
        # Workaround for special character &
        return request_string.replace('&', '%26').encode()

problem when using self signed ssl certs

Hi,

I am testing in a check_mk installation with a self-signed SSL certificate and I was getting this error:
raise URLError(err)urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)>

The crash happens here : https://github.com/brennerm/check-mk-web-api/blob/master/check_mk_web_api/__init__.py#L142-L145

In a quick google search I found a possible workaround here

I did a test and this seems to work to skip ssl validation and be able to query self-signed certs:

        import ssl
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        response = urllib.request.urlopen(
            self.__build_request_path(query_params),
            WebApi.__build_request_data(data, request_format),context=ctx
        )

Would it be possible to add an option to skip ssl validation when working with self-signed ssl certs?

Check_MK exception: Unknown tag group snmp_community

Hello,

I am facing the issue that you can't create a host with snmp-host.
The response from the exeption message says: "Check_MK exception: Unknown tag group snmp_community".

To reproduce this I created this test:

def test_add_host_with_attributes():
   api.add_host('host00', tags={'snmp_community': 'public', 'tag_snmp_ds': 'snmp-v2'})
   assert api.get_host('host00')['attributes']['snmp_community'] == 'public'
   assert api.get_host('host00')['attributes']['tag_snmp_ds'] == 'snmp-v2'

The problem is that always the 'tag_' prefix gets added so 'snmp_community' can't be found.

Removing this solved my problem.
I guess I could use the 'custom_attrs' param, but then I would need to build a special-case.
Is there a reason the the tag_ prefix gets added?

Have a nice day

python 2.7 import urllib.parse ImportError: No module named parse

root@bbcd54098726:# python --version
Python 2.7.16
root@bbcd54098726:
# python test2.py
Traceback (most recent call last):
File "test2.py", line 5, in
import check_mk_web_api
File "/usr/local/lib/python2.7/site-packages/check_mk_web_api/init.py", line 6, in
import urllib.parse
ImportError: No module named parse

My script.

import check_mk_web_api
import os, ssl
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):
    ssl._create_default_https_context = ssl._create_unverified_context


myhostname = "myhost.domain.edu"
api = check_mk_web_api.WebApi('https://checkmk.domain.edu/manage/check_mk/webapi.py', username='automation', secret='123456')

myresult = api.get_host( myhostname , effective_attributes=True)
print ( myresult )

API calls not working

Hi,

I was excited to see this Python API implementation, however it seems I cannot get it to work.
We use Check_MK Enterprise version 1.2.8p15, which version was this tested on?

Thanks!

In [4]: api.get_host("HOSTNAME")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-b7308340d256> in <module>()
----> 1 api.get_host("HOSTNAME")

/usr/lib/python3.4/site-packages/check_mk_web_api/__init__.py in get_host(self, hostname, effective_attributes)
    208         }
    209
--> 210         return self.make_request('get_host', query_params=query_params, data=data)
    211
    212     def get_all_hosts(self, effective_attributes: bool=False):

/usr/lib/python3.4/site-packages/check_mk_web_api/__init__.py in make_request(self, action, query_params, data)
    120             raise CheckMkWebApiResponseException(response)
    121
--> 122         body = json.loads(response.read().decode())
    123         result = body['result']
    124

/usr/lib64/python3.4/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    316             parse_int is None and parse_float is None and
    317             parse_constant is None and object_pairs_hook is None and not kw):
--> 318         return _default_decoder.decode(s)
    319     if cls is None:
    320         cls = JSONDecoder

/usr/lib64/python3.4/json/decoder.py in decode(self, s, _w)
    341
    342         """
--> 343         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    344         end = _w(s, end).end()
    345         if end != len(s):

/usr/lib64/python3.4/json/decoder.py in raw_decode(self, s, idx)
    359             obj, end = self.scan_once(s, idx)
    360         except StopIteration as err:
--> 361             raise ValueError(errmsg("Expecting value", s, err.value)) from None
    362         return obj, end

ValueError: Expecting value: line 1 column 1 (char 0)

Very good tool

Hi all,
thank you so much for this web api tool its really very very helpful.
I have only a question, is there a way to not install the web-api ?
I want use it beside my other python files ?

thanks in advance

Best Regards
Neeloj

How to specify refresh type?

Hi,

First of all thanks for this api wrapper!

I see that you define this:

    class DiscoverMode(enum.Enum):
        """
        new - Only discover new services
        remove - Remove exceeding services
        fixall - Remove exceeding services and discover new services
        refresh - Start from scratch
        """
        NEW = 'new'
        REMOVE = 'remove'
        FIXALL = 'fixall'
        REFRESH = 'refresh'

And then you set the discovery request to NEW:

discover_services(self, hostname: str, mode: DiscoverMode=DiscoverMode.NEW):

Can this be overridden to the other types? I have tried various ways of doing this:

api.discover_services(host,  DiscoverMode='REFRESH')
'str' object has no attribute 'value'
api.discover_services(h, 'mode:REFRESH')
'str' object has no attribute 'value'
api.discover_services(h, mode.REFRESH)
name 'mode' is not defined
api.discover_services(h, DiscoverMode.REFRESH)
name 'DiscoverMode' is not defined

I am not very proficient in python yet, but if you could give me some pointers i should be able to figure out what to change.

Default alert rules export, no API

I need to get the list of activated alerting rules, service names which are default or autodicovered.
But I see I couldn't get the list of default thresholds, service names.

Do you think you could help or guide?

Ryan

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.