0

我昨天阅读了文档并使用 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'error': {u'innererror': {u'message': u'给定的 API Key 对请求无效', u'code': u'UnsupportedKeyError'}, u'message': u'未提供有效身份验证', u'code': u'AuthorizationRequiredError'}}

这是文档的链接

4

2 回答 2

1

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

Authorization: Bearer <access token>

所以,你需要修改X-Api-Key": "{api_key}Authorization: Bearer <access token>.

您需要先创建一个服务主体,请查看此链接

然后,您可以使用 sp 获取令牌,请查看此链接

注意:您可以通过代码获取令牌,但需要将资源修改为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'
}
于 2018-03-16T04:20:08.913 回答
0

查询 OMS 或日志分析工作区的工作原型。

import adal
import requests
import json
import datetime
from pprint import pprint

# Details of workspace.  Fill in details for your workspace.
resource_group = 'xxx'
workspace = 'xxx'
workspaceid = 'xxxx'

# Details of query.  Modify these to your requirements.
query = "AzureActivity | limit 10"

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


# 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'
}
search_params = {
        "query": query
        }

url = "https://api.loganalytics.io/v1/workspaces/{workspaceID}/query"

res = requests.post(url=url, json=search_params, headers=headers)
print (res.status_code)
print (res.json())
于 2020-07-16T05:36:02.117 回答