通过 Python 高级搜寻

适用于:

  • ../microsoft-defender-endpoint.md

希望体验 Microsoft Defender for Endpoint? 注册免费试用版

注意

如果你是美国政府客户,请使用美国政府客户Microsoft Defender for Endpoint中列出的 URI。

提示

为了提高性能,可以使用离地理位置更近的服务器:

  • api-us.securitycenter.microsoft.com
  • api-eu.securitycenter.microsoft.com
  • api-uk.securitycenter.microsoft.com
  • api-au.securitycenter.microsoft.com

使用 Python 运行高级查询,请参阅 高级搜寻 API

在本部分中,我们将共享 Python 示例来检索令牌并使用它来运行查询。

先决条件:首先需要 创建应用

获取令牌

  • 运行以下命令:
import json
import urllib.request
import urllib.parse

tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here

url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)

resourceAppIdUri = 'https://api.securitycenter.microsoft.com'

body = {
    'resource' : resourceAppIdUri,
    'client_id' : appId,
    'client_secret' : appSecret,
    'grant_type' : 'client_credentials'
}

data = urllib.parse.urlencode(body).encode("utf-8")

req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]

其中

  • tenantId:要代表其运行查询的租户的 ID (即,查询对此租户的数据运行)
  • appId:Microsoft Entra应用的 ID, (应用必须具有“运行高级查询”权限才能Microsoft Defender for Endpoint)
  • appSecret:Microsoft Entra应用的机密

运行查询

运行以下查询:

query = 'DeviceRegistryEvents | limit 10' # Paste your own query here

url = "https://api.securitycenter.microsoft.com/api/advancedqueries/run"
headers = { 
    'Content-Type' : 'application/json',
    'Accept' : 'application/json',
    'Authorization' : "Bearer " + aadToken
}

data = json.dumps({ 'Query' : query }).encode("utf-8")

req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
schema = jsonResponse["Schema"]
results = jsonResponse["Results"]
  • 架构包含查询结果的架构
  • 结果包含查询的结果

复杂查询

如果要) 运行 (或多行查询的复杂查询,请将查询保存在文件中,而不是上述示例中的第一行,运行以下命令:

queryFile = open("D:\\Temp\\myQuery.txt", 'r') # Replace with the path to your file
query = queryFile.read()
queryFile.close()

处理查询结果

现在可以使用查询结果。

若要循环访问结果,请使用以下命令:

for result in results:
    print(result) # Prints the whole result
    print(result["EventTime"]) # Prints only the property 'EventTime' from the result

若要以 csv 格式输出查询结果,file1.csv 请使用以下命令:

import csv

outputFile = open("D:\\Temp\\file1.csv", 'w')
output = csv.writer(outputFile)
output.writerow(results[0].keys())
for result in results:
    output.writerow(result.values())

outputFile.close()

若要在文件中以 JSON 格式输出查询结果file1.json请使用以下命令:

outputFile = open("D:\\Temp\\file1.json", 'w')
json.dump(results, outputFile)
outputFile.close()

提示

想要了解更多信息? Engage技术社区中的 Microsoft 安全社区:Microsoft Defender for Endpoint技术社区