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: 쿼리를 실행하려는 테넌트 ID(즉, 쿼리가 이 테넌트 데이터에서 실행됨)입니다.
  • appId: Microsoft Entra 앱의 ID(앱에 '고급 쿼리 실행' 권한이 있어야 엔드포인트용 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

쿼리 결과를 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()

더 자세히 알아보고 싶으신가요? 기술 커뮤니티: 엔드포인트용 Microsoft Defender Tech Community의 Microsoft 보안 커뮤니티와 Engage.