Forum Discussion

Purnadi_K's avatar
7 years ago

A Complementing example - REST API with PowerShell

Being a newbie myself in the area of PowerShell, this is just a simple example or even 'raw' codes of PS for LogicMonitor REST API which hopefully it will be of little benefit to whomever needs it. 

I believe one of many advantages using LogicMonitor is the freedom that the other products in the market may not give and that is to deploy creativities in the existing monitoring. The example provided here is pertaining to REST API where LogicMonitor has a bunch of publication on our help page: 

Quote

 

and several code samples are inclusive in the documents. I have seen many of our great Clients have used them and even made it to next level where even our Support team (or probably limited to only myself) was 'brought to our knees' :)/emoticons/smile@2x.png 2x" title=":)" width="20">, and must admit the very advanced level these precious Clients have. What an excellent people they are!

Recently we had one nice client who asked for code sample to retrieve device in the portal, and not only few but ALL of them. We do have a sample code,  kind courtesy of our Product Team (Ms. Sarah Terry):

Quote

 

If the request is to use Python, that sample would have been sufficient, nonetheless, or I should say 'unfortunately', it requires PowerShell. As we all know that our Support Team's standard response would be to suggest our Clients making in-house development if such requirements arise or wait for our Product/Development to release a fresh sample in the abovementioned help page.

But on this occasion, using the 'cheat' sheet in the other samples, I tested the following code which gives me a satisfactory result (for a newbie certainly):

<# account info #>
$accessId = '.....[API access id].....'
$accessKey = '....[API access key].....'
$company = '.....[LogicMonitor portal/account]....'

$allDevices = @()

<# loop #>
$count = 0
$done = 0

While ($done -eq 0){

	<# request details #>
	$httpVerb = 'GET'
	$resourcePath = '/device/devices'
	$queryParams ='?offset=' + $count + '&size=3'+'&fields=id,displayName'

	<# Construct URL #>
	$url = 'https://' + $company + '.logicmonitor.com/santaba/rest' + $resourcePath + $queryParams

	<# Get current time in milliseconds #>
	$epoch = [Math]::Round((New-TimeSpan -start (Get-Date -Date "1/1/1970") -end (Get-Date).ToUniversalTime()).TotalMilliseconds)

	<# Concatenate Request Details #>
	$requestVars = $httpVerb + $epoch + $resourcePath

	<# Construct Signature #>
	$hmac = New-Object System.Security.Cryptography.HMACSHA256
	$hmac.Key = [Text.Encoding]::UTF8.GetBytes($accessKey)
	$signatureBytes = $hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($requestVars))
	$signatureHex = [System.BitConverter]::ToString($signatureBytes) -replace '-'
	$signature = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($signatureHex.ToLower()))

	<# Construct Headers #>
	$auth = 'LMv1 ' + $accessId + ':' + $signature + ':' + $epoch
	$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
	$headers.Add("Authorization",$auth)
	$headers.Add("Content-Type",'application/json')

	<# Make Request #>
	$response = Invoke-RestMethod -Uri $url -Method Get -Header $headers 

	$total = $response.data.total
	$devId = $response.data.items.id
	$numDevices = $devId.Length
	$count += $numDevices
		$items = $response.data.items
	$allDevices += $items

	if ($count -eq $total) {
		$done = 1
	}
} #end loop

Write-Host ($allDevices| ConvertTo-Json -Depth 5)

So, hopefully, somebody can sanitize the codes for the better for their own usage.

The important highlights are:

Quote

$accessId = '.....[API access id].....'
$accessKey = '....[API access key].....'
$company = '.....[LogicMonitor portal/account]....'

 

that will need to be changed accordingly, and:

Quote

$queryParams ='?offset=' + $count + '&size=3'+'&fields=id,displayName'

that depends on what fields to be displayed in the output, how many number of devices to be retrieved at one time (size=3). 

 

Note: using dummy devices in our lab portal, 11 devices can be successfully retrieved by iterating 3 at a time for 4xAPI requests. I never tested with above 1000 devices as the document mentioned to be the limit per request (although it would be nice if any of our Clients is willing to test. If only Google be our Client, great to test their two freshly-built datacenters at the far-west of Singapore with 'must-be' more than thousands of devices) :

Quote

Example Request 6: GET all devices

The following Python script will iterate through all devices, 1000 at a time, to return all devices in the account api.logicmonitor.com: