デバイスを更新する

最終更新日: 29 年 2022 月 XNUMX 日

LogicMonitorのRESTAPIを使用して、アカウント内のデバイスを更新できます。

すべてのAPI呼び出しと同様に、 認証が必要です.

デバイスを更新するには、次のXNUMXつの方法があります。

  • PUT:PUTリクエストを使用すると、デバイス定義全体を置き換える(およびプロセスのフィールドを更新する)ことができます。 デバイスの更新されたJSON定義を提供する場合は、PUTを使用してデバイスを更新する必要があります。 REST標準と一致して、PUTリクエストで指定されていないプロパティはデフォルト値に戻ることに注意してください。
  • PATCH:PATCHリクエストを使用すると、デバイスの特定のフィールドのみを置き換えることができます。 デバイスのJSON定義がなく、いくつかのフィールドのみを更新する場合は、PATCHを使用する必要があります。

PUT

REST標準と一致して、PUTリクエストで指定されていないプロパティはデフォルト値に戻ることに注意してください。 そのため、カスタムデバイスの構成やプロパティをリクエストに含める必要があります。 これを達成する簡単な方法のXNUMXつは、最初に GET 目的のデバイスをリクエストし、デバイスのJSON定義を操作してから、そのJSONをPUTリクエストで使用してデバイスを更新します(を参照)。 例として)。 難読化されたプロパティ値をXNUMXつの星として渡すと、LogicMonitorでその値が保持されます。 このプロセスを簡単にするために、PATCHメソッドを公開する予定であることに注意してください(HTTP PATCHでは、リクエストにすべてのパラメーターを含める必要がないため)。

HTTPメソッド:PUT

URI:/ device / devices / {id}

リクエストパラメータ:

プロパティ

説明

必須?

デバイスのホスト名またはIPアドレス 有り 文字列 「名前」:「10.36.11.240」
displayName デバイスの表示名 有り 文字列 “ displayName”:” ProdServer24”
PreferredCollectorId デバイスを監視するために割り当てられた優先コレクターのID 有り 整数 「preferredCollectorId」:85
hostGroupId デバイスが属するグループのID。複数のグループIDはコンマで区切る必要があります。 いいえ。デフォルトは「1」(ルートグループ)です。 文字列 「hostGroupIds」:「2,34」
説明 デバイスの説明 いいえ 文字列 「説明」:「LAデータセンターのサーバー」
無効にするアラート このデバイスでアラートが無効(true)か有効(false)かを示します いいえ。デフォルトはfalseです。 ブーリアン 「disableAlerting」:false
デバイスに関連付けられているURLリンク いいえ 文字列 「リンク」:「https://status.aws.amazon.com」
イネーブルネットフロー Netflowがデバイスに対して有効(true)か無効(false)かを示します いいえ。デフォルトはfalseです。 ブーリアン 「enableNetflow」:false
ネットフローコレクターID デバイスに関連付けられているNetFlowコレクターのID enableNetflow = trueの場合 整数 「netflowCollectorId」:125
カスタムプロパティ このデバイスのカスタムプロパティを定義します。 各プロパティには名前と値が必要です。 いいえ JSONオブジェクト “ customProperties”:[{“ name”:” snmp.version”、” value”:” v3”}、{“ name”:” location”、” value”:” Santa Barbara、CA”}]

例1:Python PUT

次のPythonスクリプトは、ID253でデバイスを更新します。

#!/bin/env python

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

#Account Info
AccessId ='48v2wRzfK94y53sq5EuF'
AccessKey ='H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
Company = 'api'

#Request Info
httpVerb ='PUT'
resourcePath = '/device/devices/253'
data = '{"name":"10.36.11.240","displayName":"ProdServer24","preferredCollectorId":90,"hostGroupIds":"2","description":"a server in the LA datacenter"}'

#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
hmac1 = hmac.new(AccessKey.encode(),msg=requestVars.encode(),digestmod=hashlib.sha256).hexdigest()
signature = base64.b64encode(hmac1.encode())

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

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

#Print status and body of response
print('Response Status:',response.status_code)
print('Response Body:',response.content)
Pythonの3

以下は、上記のリクエストに対する応答の例です。

Response Status: 200
Response Body: {
  "status" : 200,
  "errmsg" : "OK",
  "data" : {
    "id" : 253,
    "name" : "10.36.11.240",
    "displayName" : "ProdServer24",
    "deviceType" : 0,
    "relatedDeviceId" : -1,
    "currentCollectorId" : 90,
    "preferredCollectorId" : 90,
    "preferredCollectorGroupId" : 1,
    "preferredCollectorGroupName" : "@default",
    "description" : "a server in the LA datacenter",
    "createdOn" : 1458754984,
    "updatedOn" : 1470715583,
    "disableAlerting" : false,
    "autoPropsAssignedOn" : 0,
    "autoPropsUpdatedOn" : 0,
    "scanConfigId" : 0,
    "link" : "",
    "enableNetflow" : false,
    "netflowCollectorId" : 0,
    "netflowCollectorGroupId" : 0,
    "netflowCollectorGroupName" : null,
    "lastDataTime" : 0,
    "lastRawdataTime" : 0,
    "hostGroupIds" : "2",
    "sdtStatus" : "none-none-none",
    "userPermission" : "write",
    "hostStatus" : "normal",
    "alertStatus" : "confirmed-warn-none",
    "alertStatusPriority" : 1100,
    "awsState" : 1,
    "alertDisableStatus" : "none-none-none",
    "alertingDisabledOn" : null,
    "collectorDescription" : "ip-374-32-37-182.us-west-1.compute.internal",
    "netflowCollectorDescription" : null,
    "customProperties" : [ {
      "name" : "system.categories",
      "value" : ""
    } ],
    "upTimeInSeconds" : 0,
    "deletedTimeInMs" : 0,
    "toDeleteTimeInMs" : 0,
    "hasDisabledSubResource" : false,
    "manualDiscoveryFlags" : {
      "winprocess" : false,
      "linuxprocess" : false,
      "winservice" : false
    }
  }
}
Python

例2:Groovy PUT

次のGroovyスクリプトは、最初にデバイス257のJSON定義を取得するためのGETリクエストを作成し、デバイスのpreferredCollectorIdを変更してから、更新されたJSONを使用してPUTリクエストを作成します。

import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPut
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import groovy.json.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;


//define credentials and url
def accessId = 'YQQ75w6Mxx9zWIeAMq5H';
def accessKey = 'f)!Z}%spR=6en+4^s2$t32r-3=NpdQ]2T{-deI)8';
def account = 'apiAccount';
def resourcePath = "/device/devices/257"
def url = "https://" + account + ".logicmonitor.com" + "/santaba/rest" + resourcePath;

//get current time
epoch = System.currentTimeMillis();

//calculate signature
requestVars = "GET" + epoch + resourcePath;

hmac = Mac.getInstance("HmacSHA256");
secret = new SecretKeySpec(accessKey.getBytes(), "HmacSHA256");
hmac.init(secret);
hmac_signed = Hex.encodeHexString(hmac.doFinal(requestVars.getBytes()));
signature = hmac_signed.bytes.encodeBase64();

// HTTP GET
CloseableHttpClient httpclient = HttpClients.createDefault();
httpGet = new HttpGet(url);
httpGet.addHeader("Authorization" , "LMv1 " + accessId + ":" + signature + ":" + epoch);
response = httpclient.execute(httpGet);
responseBody = EntityUtils.toString(response.getEntity());
code = response.getStatusLine().getStatusCode();

response = new JsonSlurper().parseText(responseBody.toString());
device = response.data;
device.preferredCollectorId = 90;
device = JsonOutput.toJson(device)
StringEntity params = new StringEntity(device,ContentType.APPLICATION_JSON);

epoch = System.currentTimeMillis(); //get current time

requestVars = "PUT" + epoch + device + resourcePath;

// construct signature
hmac = Mac.getInstance("HmacSHA256");
secret = new SecretKeySpec(accessKey.getBytes(), "HmacSHA256");
hmac.init(secret);
hmac_signed = Hex.encodeHexString(hmac.doFinal(requestVars.getBytes()));
signature = hmac_signed.bytes.encodeBase64();

// HTTP PUT
httpPut = new HttpPut(url);
httpPut.addHeader("Authorization" , "LMv1 " + accessId + ":" + signature + ":" + epoch);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
httpPut.setEntity(params);
responsePut = httpclient.execute(httpPut);
responseBodyPut = EntityUtils.toString(responsePut.getEntity());
codePut = responsePut.getStatusLine().getStatusCode();

// Print Response
println "Status:" + codePut;
println "Response body:" + responseBodyPut;
httpclient.close();
Groovy

PATCH

HTTPメソッド:PATCH

URI:/ device / devices / {id}

リクエストパラメータ:

すべてのPATCHリクエストには、クエリパラメータを含める必要があります パッチフィールド これは、更新する必要があるフィールドを示します。複数のフィールドはコンマで区切る必要があります。 フィールドがpatchFieldsパラメータで識別され、リクエストのペイロードに含まれている場合、その値は更新されます。 他のすべてのフィールド値は同じままです。 たとえば、デバイスの名前を更新する場合、URI +クエリパラメータは/ santaba / rest / device / devices / {id}?patchFields = Nameになります。 名前フィールドもリクエストペイロードに含める必要があります。 次のフィールドは、PATCHを介して更新できます。

プロパティ

説明

デバイスのホスト名またはIPアドレス 文字列 「名前」:「10.36.11.240」
displayName デバイスの表示名 文字列 “ displayName”:” ProdServer24”
PreferredCollectorId デバイスを監視するために割り当てられた優先コレクターのID 整数 「preferredCollectorId」:85
hostGroupId デバイスが属するグループのID。複数のグループIDはコンマで区切る必要があります。 文字列 「hostGroupIds」:「2,34」
説明 デバイスの説明 文字列 「説明」:「LAデータセンターのサーバー」
無効にするアラート このデバイスでアラートが無効(true)か有効(false)かを示します ブーリアン 「disableAlerting」:false
デバイスに関連付けられているURLリンク 文字列 「リンク」:「https://status.aws.amazon.com」
イネーブルネットフロー Netflowがデバイスに対して有効(true)か無効(false)かを示します ブーリアン 「enableNetflow」:false
ネットフローコレクターID デバイスに関連付けられているNetFlowコレクターのID 整数 「netflowCollectorId」:125
カスタムプロパティ このデバイスのカスタムプロパティを定義します。 各プロパティには名前と値が必要です。 customPropertiesオブジェクトのXNUMXつまたはいくつかのデバイスプロパティを追加または更新するには、すべてではありませんが、opTypeクエリパラメータを追加で使用する必要があります。 opTypeクエリパラメータは、追加、更新、または置換するように設定できます。 opType = add ペイロードに含まれるプロパティが追加されるが、既存のすべてのプロパティは同じままであることを示します。 opType = replace リクエストペイロードに含まれるプロパティがまだ存在しない場合は追加され、存在する場合は更新されますが、他のすべての既存のプロパティは同じままであることを示します。 opType = refresh プロパティがリクエストペイロードに含まれるプロパティに置き換えられることを示します。 JSONオブジェクト “ customProperties”:[{“ name”:” snmp.version”、” value”:” v3”}、{“ name”:” location”、” value”:” Santa Barbara、CA”}]

例1:Python PATCH

次のPythonスクリプトは、Netflowを有効にし、デバイス435のNetflowコレクターを設定しますが、他のすべてのデバイスフィールドはそのままにします。

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

#Account Info
AccessId ='48v2wRzfK94y53sq5EuF'
AccessKey ='H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
Company = 'api'

#Request Info
httpVerb ='PATCH'
resourcePath = '/device/devices/435'
queryParams = '?patchFields=enableNetflow,netflowCollectorId'
data = '{"enableNetflow":true,"netflowCollectorId":85}'

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

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

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

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

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

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

#Print status and body of response
print('Response Status:',response.status_code)
print('Response Body:',response.content)
Pythonの3

例2:Python PATCH

次のPythonスクリプトは、デバイス435のプロパティを追加しますが、他のすべてのデバイスフィールドはそのままにします。

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

#Account Info
AccessId ='48v2wRzfK94y53sq5EuF'
AccessKey ='H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
Company = 'api'

#Request Info
httpVerb ='PATCH'
resourcePath = '/device/devices/435'
queryParams = '?patchFields=customProperties&opType=add'
data = '{"customProperties":[{"name":"snmp.version","value":"v2c"}]}'

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

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

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

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

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

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

#Print status and body of response
print('Response Status:',response.status_code)
print('Response Body:',response.content)
Pythonの3

例3:Python PATCH

次のPythonスクリプトは、表示名に「prod」が含まれるすべてのデバイスのコレクターIDを更新し、デバイスの他のすべてのフィールドをそのままにします。

#!/bin/env python

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

#Account Info
AccessId ='48v2wRzfK94y53sq5EuF'
AccessKey ='H_D9i(f5~B^U36^K6i42=^nS~e75gy382Bf6{)P+'
Company = 'api'

#Request Info
httpVerb ='GET'
resourcePath = '/device/devices'
queryParam = '?filter=displayName~prod'

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

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

#Concatenate Request details
requestVars = httpVerb + epoch + resourcePath

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

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

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

#Parse response
jsonResponse = json.loads(response.content)

#Loop through each device & update Collector Id
for i in jsonResponse['data']['items']:
    deviceId = str(i['id'])

    #Request Info
    httpVerb ='PATCH'
    resourcePath = '/device/devices/'+deviceId
    queryParams ='?patchFields=preferredCollectorId'
    data = '{"preferredCollectorId":85}'

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

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

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

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

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

    #Make request
    response = requests.patch(url, data=data, headers=headers)
Pythonの3
記事上で