Forum Discussion

Tanvir's avatar
7 years ago

Create Dynamic group by Script

Hi Members

I am trying to create 'Device Dynamic Groups' with Python script. but I am failing. Could you pleas me what I am missing:

Conditions of the groups name: If Device display name starts with prod, all device should group.  

data = '{"name":"test111","parentId":111,"appliesTo":"startsWith("system.displayname","Prod")"}'

I have attached the full script too. I am running Python 3.6.5

#!/bin/env python

import requests
import json
import hashlib
import base64
import time
import hmac

#Account Info
AccessId ='XXXXXX'
AccessKey ='XXXXXX'
Company = 'contoso'

#Request Info
httpVerb ='POST'
resourcePath = '/device/groups'
data = '{"name":"test111","parentId":111,"appliesTo":"startsWith("system.displayname","Prod")"}'

#Construct URL 
url = 'https://'+ Company +'.logicmonitor.com/santaba/rest' + resourcePath 

#Get current time in milliseconds
epoch = str(int(time.time() * 1000))

#Concatenate Request details
requestVars = httpVerb + epoch + data + resourcePath

#Construct signature
#signature = base64.b64encode(hmac.new(AccessKey,msg=requestVars,digestmod=hashlib.sha256).hexdigest())
hmac = hmac.new(AccessKey.encode(),msg=requestVars.encode(),digestmod=hashlib.sha256).hexdigest()
signature = base64.b64encode(hmac.encode())

#Construct headers
#auth = 'LMv1 ' + AccessId + ':' + signature + ':' + epoch
#headers = {'Content-Type':'application/json','Authorization':auth}
auth = 'LMv1 ' + AccessId + ':' + signature.decode() + ':' + epoch
headers = {'Content-Type':'application/json','Authorization':auth}

#Make request
response = requests.post(url, data=data, headers=headers)

 

Please assist

Thank you.

  • Just another random note lol.. I read YAML better so I'm always using https://www.json2yaml.com/

    name: test111
    parentId: 111
    appliesTo:  startsWith("system.displayname","Prod")

    translates to

    { "name": "test111", "parentId": 111, "appliesTo": "startsWith(\"system.displayname\",\"Prod\")" }

     

    *shrug* :)/emoticons/smile@2x.png 2x" title=":)" width="20">

  • On 4/8/2018 at 11:22 PM, Tanvir said:
    
    data = '{"name":"test111","parentId":111,"appliesTo":"startsWith("system.displayname","Prod")"}'

     

    Your payload in the data variable is not valid JSON. So here you'll want to escape certain special/reserved characters which would otherwise render your JSON invalid. In this example, this would include the double-quotes, so it should look like this---

    data = '{"name":"test111","parentId":111,"appliesTo":"startsWith(\"system.displayname\",\"Prod\")"}'

    Using a JSON validator like https://jsonformatter.curiousconcept.com/  will probably help.

  • Thanks Joe data =  '{\"name\":\"test1111\",\"parentId\":111,\"appliesTo\": \"Type==\\\"Test Server\\\"\"}' worked