是否可以从Azure Python SDK获取ASC位置?

2024-04-27 11:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Microsoft Azure Security Center (ASC) Management Client Library获取订阅的安全分数。库中的所有操作状态为

You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.

因此,我正在使用以下规范创建SecurityCenter客户端:

SecurityCenter(credentials, subscription_id, asc_location, base_url=None)

然而,在我看来,正确获取asc_location信息的唯一方法是使用SecurityCenter客户端获取它The spec与上面的引文相同,You should not instantiate...。因此,我无法创建客户端,因为我需要ASC位置来创建客户端,我需要创建客户端来获取ASC位置

文件中提到

The location where ASC stores the data of the subscription. can be retrieved from Get locations

在pythonsdk文档中搜索这个“getlocations”,除了restapi之外,我什么都没有得到。我错过什么了吗?我们是否应该从SDK存储库中硬编码位置,如this SO postthis GitHub issue


Tags: theclientyou客户端createnotitlocation
2条回答

正如官方API参考list locations所示:

The location of the responsible ASC of the specific subscription (home region). For each subscription there is only one responsible location.

它不会更改,因此如果您已经知道订阅的asc_location的值,则可以硬编码此值

但每个订阅可能具有不同的asc\U位置值(my 2 Azure订阅具有不同的asc\U位置值)。 因此,如果您有很多Azure订阅,您可以通过API查询asc_location据我所知,这是我能找到的唯一方法),然后使用SDK获得安全分数,请尝试以下代码:

from azure.mgmt.security import SecurityCenter
from azure.identity import ClientSecretCredential
import requests
from requests.api import head, request 

TENANT_ID = ''
CLIENT = ''
KEY = ''
subscription_id= ''
getLocationsURL = "https://management.azure.com/subscriptions/"+subscription_id+"/providers/Microsoft.Security/locations?api-version=2015-06-01-preview"


credentials = ClientSecretCredential(
    client_id = CLIENT,
    client_secret = KEY,
    tenant_id = TENANT_ID
)

#request for asc_location for a subscription
azure_access_token = credentials.get_token('https://management.azure.com/.default')
r = requests.get(getLocationsURL,headers={"Authorization":"Bearer " +  azure_access_token.token}).json()
location = r['value'][0]['name']
print("location:" + location)

client = SecurityCenter(credentials, subscription_id, asc_location=location)
for score in client.secure_scores.list():
    print(score)

结果: enter image description hereenter image description here

我最近遇到了这个问题

根据我的观察,我可以使用订阅下的任何位置启动SecurityCenter客户端。然后稍后client.locations.list()正好给我一个ASC位置

# Any of SubscriptionClient.subscriptions.list_locations will do
location = 'eastasia'

client = SecurityCenter(
            credential, my_subscription_id,
            asc_location=location
        )

data = client.locations.list().next().as_dict()
pprint(f"Asc location: {data}")

在我的例子中,不管我的输入是eastasia,它总是westcentralus

请注意,如果使用get而不是list,您将得到异常

data = client.locations.get().as_dict()
pprint(f"Asc location: {data}")
# azure.core.exceptions.ResourceNotFoundError: (ResourceNotFound) Could not find location 'eastasia'

所以我做的有点尴尬

  1. 使用“我的订阅”下的位置创建SecurityCenter客户端
  2. client.locations.list()以获取ASC位置
  3. 使用检索到的ASC位置再次创建SecurityCenter客户端

相关问题 更多 >