如何从OMS工作区获取数据

时间:2018-03-16 02:51:59

标签: python-2.7 azure azure-log-analytics azure-oms

我昨天阅读了文档并使用python进行了一些编码,以便按以下方式获取数据。它工作正常。

import logging as log
import adal
import requests
import json
import datetime
from pprint import pprint

# Details of workspace.  Fill in details for your workspace.
resource_group = 'Test'
workspace = 'FirstMyWorkspace'

# Details of query.  Modify these to your requirements.
query = "Type=*"
end_time = datetime.datetime.utcnow()
start_time = end_time - datetime.timedelta(hours=24)
num_results = 2  # If not provided, a default of 10 results will be used.

# IDs for authentication.  Fill in values for your service principal.
subscription_id = '{subscription_id}'
tenant_id = '{tenant_id}'
application_id = '{application_id}'
application_key = '{application_key}'



# URLs for authentication
authentication_endpoint = 'https://login.microsoftonline.com/'
resource  = 'https://management.core.windows.net/'

# Get access token
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token_response = context.acquire_token_with_client_credentials('https://management.core.windows.net/', application_id, application_key)
access_token = token_response.get('accessToken')
# Add token to header
headers = {
    "Authorization": 'Bearer ' + access_token,
    "Content-Type": 'application/json'
}

# URLs for retrieving data
uri_base = 'https://management.azure.com'
uri_api = 'api-version=2015-11-01-preview'
uri_subscription = 'https://management.azure.com/subscriptions/' + subscription_id
uri_resourcegroup = uri_subscription + '/resourcegroups/'+ resource_group
uri_workspace = uri_resourcegroup + '/providers/Microsoft.OperationalInsights/workspaces/' + workspace
uri_search = uri_workspace + '/search'

# Build search parameters from query details
search_params = {
        "query": query,
        "top": num_results
        }

# Build URL and send post request
uri = uri_search + '?' + uri_api
response = requests.post(uri, json=search_params,headers=headers)

# Response of 200 if successful
if response.status_code == 200:

    # Parse the response to get the ID and status
    data = response.json()
    if data.get("__metadata", {}).get("resultType", "") == "error":
        log.warn("oms_fetcher;fetch_job;error: " + ''.join('{}={}, '.format(key, val) for key, val in
                                                           data.get("error", {}).items()))
    else:
        print data["value"]
        search_id = data["id"].split("/")
        id = search_id[len(search_id)-1]
        status = data["__metadata"]["Status"]
        print status
        # If status is pending, then keep checking until complete
        while status == "Pending":

            # Build URL to get search from ID and send request
            uri_search = uri_search + '/' + id
            uri = uri_search + '?' + uri_api
            response = requests.get(uri, headers=headers)

            # Parse the response to get the status
            data = response.json()
            status = data["__metadata"]["Status"]
        print id

else:

    # Request failed
    print (response.status_code)
    response.raise_for_status()

今天我去了昨天我所遵循的同一个网页,但今天有一个不同的文档。那么我需要遵循新的文档吗?我也尝试了新的文档,但遇到了问题

url = "https://api.loganalytics.io/v1/workspaces/{workspace_id}/query"
headers = {
    "X-Api-Key": "{api_key}",
    "Content-Type": 'application/json'
}
search_param = {

}

res = requests.post(url=url, json=search_param, headers=headers)
print res.status_code
print res.json()
  

{u'错误':{u' innererror':{u' message':u'给定的API密钥不是   适用于请求','代码&#39 ;: u' UnsupportedKeyError'},u' message':   u'未提供有效身份验证',u' code':   U' AuthorizationRequiredError'}}

以下是documentation

的链接

2 个答案:

答案 0 :(得分:1)

api_key不是Portal上的主键。您可以查看此link中的示例。令牌应如下所示:

Authorization: Bearer <access token>

因此,您需要将X-Api-Key": "{api_key}修改为Authorization: Bearer <access token>

首先需要创建服务主体,请检查link

然后,您可以使用sp获取令牌,请检查此link

注意:您的代码可以获取令牌,但您需要将资源修改为https://api.loganalytics.io。如下所示:

# Get access token
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.io', application_id, application_key)
access_token = token_response.get('accessToken')
# Add token to header
headers = {
    "Authorization": 'Bearer ' + access_token,
    "Content-Type": 'application/json'
}

答案 1 :(得分:0)

用于查询OMS或Log Analytic工作区的工作原型。

$url = "https://graph.facebook.com/$id/posts?access_token=$accessToken&fields=full_picture,message,...";