Testing the SCOM REST API with a Python script

In some cases, the SCOM Data Source for Grafana may fail to connect to SCOM. To troubleshoot the issue, you can use a Python script to verify the connection.

To troubleshoot the connection to the SCOM REST API, you can use the script below. Make sure that the followin variables reflect your environment:
$URIBase = 'http://<FQDN>/OperationsManager'
$userName ="contoso\\administrator";
$password ="*********";

 

import requests
import base64
import json
from urllib.parse import unquote
import getpass

# SCOM REST API Url
uri_base = "<FQDN>/OperationsManager"

# Set credentials and authentication mode
username = "contoso\\administrator"
password = "*********"  # Alternatively, use: password = getpass.getpass("Password: ")
authentication_mode = "Network"

# Build headers for the request
headers = {
    "Content-Type": "application/json; charset=utf-8"
}

# Prepare the authentication payload
body_raw = f"({authentication_mode}):{username}:{password}"
encoded_text = base64.b64encode(body_raw.encode("utf-8")).decode("utf-8")
json_body = json.dumps(encoded_text)

# Create a session to persist cookies across requests
session = requests.Session()

# Authenticate by posting to the authentication endpoint.
auth_response = session.post(f"{uri_base}/authenticate", headers=headers, data=json_body, auth=(username, password))
if auth_response.status_code != 200:
    print("Authentication failed:", auth_response.status_code)
    exit()

# Retrieve the CSRF token from session cookies and add it to the headers
csrf_token = session.cookies.get("SCOM-CSRF-TOKEN")
if csrf_token:
    decoded_token = unquote(csrf_token)
    headers["SCOM-CSRF-TOKEN"] = decoded_token
else:
    print("CSRF token not found.")

# Prepare the criteria for the next API call
criteria = "DisplayName LIKE '%Windows%'"
json_criteria = json.dumps(criteria)

# URL for invoking the SCOM API (for monitors)
# Call the API using the authenticated session, with credentials and CSRF token
monitors_response = session.post(f"{uri_base}/data/class/monitors", headers=headers, data=json_criteria, auth=(username, password))
if monitors_response.status_code == 200:
    try:
        response_json = monitors_response.json()
        # Print the alerts in formatted JSON
        print(response_json)
    except Exception as e:
        print("Error processing JSON response:", e)
else:
    print("Failed to retrieve monitors:", monitors_response.status_code)