首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python的Azure rest

使用Python的Azure rest
EN

Stack Overflow用户
提问于 2022-04-13 11:41:37
回答 1查看 791关注 0票数 1

我对Azure很陌生。我需要设置一个自动化脚本,使用Python APi列出所有的Ips。但是,我无法从传递给请求的API url中获得任何结果。

我在跟踪这个https://learn.microsoft.com/en-us/rest/api/virtualnetwork/public-ip-addresses/list-all#code-try-0

在代码块中,我尝试使用请求。

代码语言:javascript
复制
import requests


apijson = requests.get("https://management.azure.com/subscriptions/9540b342-9f94-4dd9-9eca-0698dda0107c/providers/Microsoft.Network/publicIPAddresses?api-version=2021-05-01"

我知道我需要设置Oauth/身份验证,但是我不知道我需要声明什么或者从我的脚本中传递任何令牌

EN

回答 1

Stack Overflow用户

发布于 2022-04-14 04:35:54

我知道我需要设置Oauth/身份验证,但是我不知道我需要声明什么或者从我的脚本中传递任何令牌

您可以声明/传递令牌,例如:

代码语言:javascript
复制
import sys
import requests
import json
import time

test_api_url = "Add URL which you want to test"


#function to obtain a new OAuth 2.0 token from the authentication server

def get_new_token():
    auth_server_url = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'"
    client_id = 'XXXX-XXXX-XXXX'
    client_secret = 'XXXX'

    token_req_payload = {'grant_type': 'client_credentials'}

    token_response = requests.post(auth_server_url,
    data=token_req_payload, verify=False, allow_redirects=False,
    auth=(client_id, client_secret))
             
if token_response.status_code !=200:
            print("Failed to obtain token from the OAuth 2.0 server", file=sys.stderr)
            sys.exit(1)

            print("Successfuly obtained a new token")
            tokens = json.loads(token_response.text)
            return tokens['access_token']

token = get_new_token()

while True:

    api_call_headers = {'Authorization': 'Bearer ' + token}
    api_call_response = requests.get(test_api_url, headers=api_call_headers, 
    verify+False)


if  api_call_response.status_code == 401:
    token = get_new_token()
else:
    print(api_call_response.text)

time.sleep(30)

您可以参考如何在Azure上验证和授权Python应用程序Azure AD身份验证Python使用OAuth 2.0与Azure Active和API管理一起保护API

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71856894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档