Python Requests

FIrst, apologies if this question has already been asked. I’m trying to retrieve info all the servers/services that are down using a Python script. But the main issue is that I can’t even get it to properly connect checkmk. I’ve tried several ways but all for naught. I’m not even sure on what the correct address should be. I’d appreciate it if you could show me a sample script on at least how to connect and get a 200 reply.

import requests
from requests.auth import HTTPBasicAuth

checkmk_username = 'abc'
checkmk_password = 'abc'
checkmk_secret = 'abc'
checkmk_url = f'http://10.17.13.233/console/check_mk/api/1.0/ui/#/Downtimes/cmk.gui.plugins.openapi.endpoints.downtime.show_downtime'

service_problems_endpoint = "/get_service_problems"

api_full_url = checkmk_url

params = {
    "_username": checkmk_username,
    "_secret": checkmk_secret,
    "_transid": "1"
}

response = requests.get(api_full_url, params=params, auth=HTTPBasicAuth(checkmk_username, checkmk_password))

if response.status_code == 200:
    service_problems = response.json()
    print(service_problems)
else:
    print(f"Error: {response.status_code} - {response.text}")
Error: 401 - {"title": "You need to be authenticated to use the REST API.", "status": 401}

Thank you in advance for your time and willingness to help!

This is the problem i would say. In the old WebAPI you had these URL variables.
Now with the REST-API the request looks like this.

#!/usr/bin/env python3
import pprint
import requests

HOST_NAME = "localhost"
SITE_NAME = "SITENAME"
API_URL = f"http://{HOST_NAME}/{SITE_NAME}/check_mk/api/1.0"

USERNAME = "automation"
PASSWORD = "test123"

session = requests.session()
session.headers['Authorization'] = f"Bearer {USERNAME} {PASSWORD}"
session.headers['Accept'] = 'application/json'

resp = session.get(
    f"{API_URL}/domain-types/downtime/collections/all",
    params={ 
        "downtime_type": 'host',  # The type of the downtime to be listed.
    },
)

This example is directly from the docs of the API.
You find this here.
image

1 Like

Hey, thank you for your answer. I tried your suggestion, but it won’t connect. I keep getting either 400 or 401. Now, which credentials should I use to connect? The one I normally use to log into the web console or the one I created for the python user? The python user also has a secret, is that the password I need to use? Well, I tried every combo and it’s all the same (400 or 401). Thank you for your help!

It looks like the auth problem has been resolved since I don’t get 401 any longer. The problem now is a 400 bad request, which I can’t figure out why.

#!/usr/bin/env python3
import pprint
import requests

HOST_NAME = "10.17.13.233"
SITE_NAME = "console"
API_URL = f"http://{HOST_NAME}/{SITE_NAME}/check_mk/api/1.0"

USERNAME = "abc"
PASSWORD = "abc!"

session = requests.session()
session.headers['Authorization'] = f"Bearer {USERNAME} {PASSWORD}"
session.headers['Accept'] = 'application/json'

resp = session.post(
    f"{API_URL}/domain-types/downtime/collections/host",
    headers={
        "Content-Type": 'application/json',
    },
    json={
        'start_time': '2023-11-19T17:32:28Z',
        'end_time': '2023-11-20T17:32:28Z',
        'recur': 'hour',
        'duration': 3600,
        'comment': 'Security updates',
        'downtime_type': 'host',
        'host_name': '10.17.13.233'
    },
)
if resp.status_code == 200:
    pprint.pprint(resp.json())
elif resp.status_code == 204:
    print("Done")
else:
    raise RuntimeError(pprint.pformat(resp.json()))
    raise RuntimeError(pprint.pformat(resp.json()))
RuntimeError: {'detail': 'These fields have problems: host_name',
 'fields': {'host_name': ["Host '10.17.13.233' exists, but is not monitored. "
                          'Activate the configuration?']},
 'status': 400,
 'title': 'Bad Request'}