0

My script looks like

import requests
import base64
user="domain\\username"
pass="password"
Authentication_mode="Windows"
tok=Authentication_mode+":"+user+":"+pass #referring the doc for authentication at https://learn.microsoft.com/en-us/rest/api/operationsmanager/authentication/login

token=base64.b64encode(bytes(token,'utf-8')).decode()
headers={'content-type':'application/json',
         'Authorization': 'Basic %s' % token
}
payload={}
url="http://<Servername>/OperationsManager/authenticate"
respone=requests.post(url,headers=headers,data=payload)
print(response)



I am getting the response code 401 instead of 200. FYI I have tried NTLM auth(gives error 400),HTTPBasicauth, HTTPDigestAuth.

The Powershell script which is given at https://community.squaredup.com/answers/question/scom-1801-rest-api/ ,I want to do this with Python.

$scomHeaders = New-Object “System.Collections.Generic.Dictionary[[String],[String]]”
$scomHeaders.Add(‘Content-Type’,’application/json; charset=utf-8′)

$bodyraw = “Windows”
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($bodyraw)
$EncodedText =[Convert]::ToBase64String($Bytes)
$jsonbody = $EncodedText | ConvertTo-Json

$uriBase = ‘http://xxxxxx/OperationsManager/authenticate’
$auth = Invoke-RestMethod -Method POST -Uri $uriBase -Headers $scomheaders -body $jsonbody -UseDefaultCredentials -SessionVariable websession



$query = @($query = @(    @{ “classid” = “” “displayColumns”=  “severity”, “monitoringobjectdisplayname”, “name”, “age”, “repeatcount”, “lastModified” })

$jsonquery = $query | ConvertTo-Json
$Response = Invoke-WebRequest -Uri “http://xxxxxx/OperationsManager/data/alert” -Method Post -Body $jsonquery -ContentType “application/json” -UseDefaultCredentials -WebSession $websession
$alerts = ConvertFrom-Json -InputObject $Response.Content
$alerts.rows | select monitoringobjectdisplayname,name,severity,age
codebee
  • 1
  • 1

1 Answers1

0

The first thing I would recommend is letting Microsoft create your credential body for authN. On the SCOM server (or any Windows box) run this powershell code.

$creds = Get-Credential
$bodyraw = "AuthenticationMode:$($creds.UserName):$($creds.GetNetworkCredential().Password)"
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($bodyraw)
$EncodedText =[Convert]::ToBase64String($Bytes)
Write-Host $EncodedText

Copy that output value and put it as the value of your jsonbody variable. Surround the value with single quotes. You will only need to update it, if you change the password for the account.

Next up, your header for the authN call needs to be:

{'Content-Type': 'application/json; charset=utf-8'}

You don't need the Authorization part of the header, we add the authN value to the post body. For example:

response = requests.Request( "Post", 'https://<your_scom_endpoint>/OperationsManager/authenticate', headers=headers, data = jsonbody )

This gets you in the door, but there are a couple of more gotchas waiting for you when you try to pull data back.

Your response should give back two cookies. One is your SCOMSessionID, and the second is your SCOM-CSRF-TOKEN. Before we try to send those back we need to URL decode the CSRF-Token. import urllib then:

decodedToken = urllib.unquote(response.cookies['SCOM-CSRF-TOKEN'])
headers.update({'SCOM-CSRF-TOKEN': decodedToken})
headers.update({'Cookie': "SCOMSessionId=" + response.cookies['SCOMSessionId']})

Now, that we have our header updated to include our cookies, we can ask for something useful. Here's an example of pulling critical alerts.

scom_alerts_body = "{\"criteria\":\"((Severity = '2') AND (ResolutionState = '0'))\",\"displayColumns\":[\"severity\",\"monitoringobjectdisplayname\",\"name\",\"age\",\"repeatcount\"],\"classId\":\"\"}"
response = requests.request( "POST", 'https://monitoring.ad.cdc.nicusa.com/OperationsManager/data/alert', headers=headers, data = scom_alerts_body )
print(response.json())

Here's a full example:

#!/bin/python

import json
import requests
import urllib

scom_authN_Uri = 'https://<scom_server>/OperationsManager/authenticate'
scom_alerts_Uri = 'https://<scom_server>/OperationsManager/data/alert'
scomHeader = {'Content-Type': 'application/json; charset=utf-8'}
scom_authN_body = '<utf-8 and base64 encoded token>'
scom_alerts_body = "{\"criteria\":\"((Severity = '2') AND (ResolutionState = '0'))\",\"displayColumns\":[\"severity\",\"monitoringobjectdisplayname\",\"name\",\"age\",\"repeatcount\"],\"classId\":\"\"}"

# Authentication Request
response = requests.request( "POST", scom_authN_Uri, headers=scomHeader, data = scom_authN_body )

# Create authN header for pulling data
decodeToken = urllib.unquote(response.cookies['SCOM-CSRF-TOKEN'])
scomHeader.update({'SCOM-CSRF-TOKEN': decodeToken})
scomHeader.update({'Cookie': "SCOMSessionId=" + response.cookies['SCOMSessionId']})

# Request Critical alerts
response = requests.request( "POST", scom_alerts_Uri, headers=scomHeader, data = scom_alerts_body )
print(response.json())

I just went through a similar task of creating a non-powershell script to retrieve SCOM Alerts. It was not easy to find the info, and I passed this post several times in my Google quest. So, hopefully this helps.

RickLFK
  • 44
  • 2
  • 8