Share via


使用 Python 進階搜尋

適用於:

想要體驗適用於端點的 Microsoft Defender 嗎? 注册免費試用版。

注意事項

如果您是美國政府客戶,請使用美國政府客戶 適用於端點的 Microsoft Defender 中所列的 URI。

提示

為了獲得更好的效能,您可以使用更接近您地理位置的伺服器:

  • us.api.security.microsoft.com
  • eu.api.security.microsoft.com
  • uk.api.security.microsoft.com
  • au.api.security.microsoft.com
  • swa.api.security.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:代表您要執行查詢的租使用者標識碼 (也就是說,查詢會在此租用戶的數據上執行)
  • appId:應用程式必須具有「執行進階查詢」許可權 (Microsoft Entra 應用程式的標識碼,才能 適用於端點的 Microsoft Defender)
  • 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

若要以檔案 file1.csv 以 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()

若要以檔案file1.json以 JSON 格式輸出查詢結果,請使用下列命令:

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

提示

想要深入了解? Engage 技術社群中的 Microsoft 安全性社群:適用於端點的 Microsoft Defender 技術社群。