如何使用 Azure python sdk 查询服务主体详细信息

How to query service principle details with service principle with Azure python sdk

我想用 Azure python SDK 查询服务原理过期数据时间。我已经有一个具有“GlobalReader”权限的服务原则。我可以使用以下代码进行身份验证。

>>> from azureml.core.authentication import ServicePrincipalAuthentication
>>> x=ServicePrincipalAuthentication(tenant_id=tenant_id, service_principal_id=client_id, service_principal_password=client_secret)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cached_arm_token', '_cached_azureml_client_token', '_cached_graph_token', '_check_if_subscription_exists', '_cloud_type', '_enable_caching', '_get_adal_auth_object', '_get_all_subscription_ids', '_get_aml_resource_id', '_get_arm_end_point', '_get_arm_token', '_get_azureml_client_token', '_get_cloud_suffix', '_get_cloud_type', '_get_graph_token', '_get_service_client', '_get_sp_credential_object', '_get_workspace', '_initialize_sp_auth', '_is_token_expired', '_service_principal_id', '_service_principal_password', '_sp_auth_lock', '_tenant_id', '_token_type_to_field_dict', 'get_authentication_header', 'signed_session']
>>>
>>>
>>> x._get_all_subscription_ids
<bound method ServicePrincipalAuthentication._get_all_subscription_ids of <azureml.core.authentication.ServicePrincipalAuthentication object at 0x7f0a174443d0>>
>>> x._get_all_subscription_ids()

如何获取其他服务原则过期详情?像 az ad sp credential list --id "[ID]" --query "[].endDate" -o tsv.

更新 1

我想我需要查看 azure-graphrbac 模块。我从this issueaz ad sp crendential list的debug看到,有方法graph_client.applications.list_password_credentials(app_object_id),但不知道怎么用

试试这个:

from azureml.core.authentication import ServicePrincipalAuthentication
import requests,json

tenantId = '<tenant id>'

query_SP_object_id = '<object ID of SP you want to query>'

x=ServicePrincipalAuthentication(tenant_id= tenantId , service_principal_id='<sp id>', service_principal_password='<sp secret>')

reqURL = 'https://graph.windows.net/'+tenantId +'/applications/'+ query_SP_object_id +'/passwordCredentials?api-version=1.6'
result = requests.get(reqURL,headers={"Authorization":'Bearer ' + x._get_graph_token()}).text

print(json.loads(result)['value'])

结果:

请注意,在这种情况下,我们使用 sp 对象 ID: