brennerm / check-mk-web-api Goto Github PK
View Code? Open in Web Editor NEWPython library to talk to the Check_Mk Web API
Home Page: https://brennerm.github.io/check-mk-web-api/
License: MIT License
Python library to talk to the Check_Mk Web API
Home Page: https://brennerm.github.io/check-mk-web-api/
License: MIT License
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()
Hi ;-)
So, one thing I had postponed a month back and just returned to:
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.
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
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?
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
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.
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
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)
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.
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
As per this https://checkmk.com/check_mk-werks.php?werk_id=6689
get_all_sites works via curl but I don't see that interface in your release
Thank you!
Hi Max,
could you add support for Kerberos Authentication?
Best, Chris
root@bbcd54098726:# python --version# python test2.py
Python 2.7.16
root@bbcd54098726:
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 )
With the release of checkmk 2.0 there will be a new REST API. We should add support for it as soon as it's available.
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
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.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.