【Azure 应用服务】使用Python Azure SDK 来获取 App Service的访问限制信息(Access Restrictions)

azure,应用服务,使用,python,sdk,获取,app,service,访问,限制,信息,access,restrictions · 浏览次数 : 33

小编点评

```python import os from azure.identity import ClientSecretCredential, AzureAuthorityHostsfrom msrestazure.azure_cloud import AZURE_CHINA_CLOUDfrom azure.mgmt.web import WebSiteManagementClientsubscription_id = os.environ['AZURE_SUBSCRIPTION_ID'] # Create a credential object with required parameters credentials = ClientSecretCredential( client_id=os.environ['AZURE_CLIENT_ID'], client_secret=os.environ['AZURE_CLIENT_SECRET'], tenant_id=os.environ['AZURE_TENANT_ID'], authority=AzureAuthorityHosts.AZURE_CHINA ) # Create a WebSiteManagementClient object web_client = WebSiteManagementClient(credentials, subscription_id, base_url=myapp_base_url, credential_scopes=[ AZURE_CHINA_CLOUD.endpoints.management + "/.default" ]) # Get the list of web apps sites = web_client.web_apps.list_by_resource_group(resource_group_name) # Print properties of each web app for site in sites: print_item(site) # Get the configuration for a specific web app site_name = "testwebapp04" configs = web_client.web_apps.get_configuration(resource_group_name, site_name) # Print IP security restrictions of the web app print_ipsecurityrestrictions(configs.ip_security_restrictions) # Create or update the configuration for the web app web_client.web_apps.create_or_update_configuration(site_name, configs) ``` **Note:** * Replace `AZURE_SUBSCRIPTION_ID` with your Azure subscription ID. * Replace `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET` with your Azure application credentials' client ID and client secret. * Replace `myapp_base_url` with your Azure App Service resource group base URL. * The `print_item()` function is a helper function that prints the properties of an Azure model. * The `print_ipsecurityrestrictions()` function prints the IP security restrictions of a web app.

正文

问题描述

为Azure App Service添加访问限制,需要Python Azure SDK来实现的示例代码。

问题解答

查阅Azure App Service的官方资料,使用Python SDK有 azure-mgmt-web 包中的 WebSiteManagementClient 类可以对Azure App Service资源进行管理。 

Access Restrictions属于App Service的配置项,所以可以通过 client类中的 web_apps.get_configuration 获取,及通过 web_apps.create_or_update_configuration 进行创建或修改。

get_configuration 方法的返回数据类型为 SiteConfig,其中包含了 ip_security_restrictions 属性值。而且它是一个List类型,其数据结构类型为 IpSecurityRestriction
 
综上所述,通过Python SDK获取App Service的Access Restrictions的示例代码如下:
import os
from azure.identity import ClientSecretCredential, AzureAuthorityHosts

from msrestazure.azure_cloud import AZURE_CHINA_CLOUD
from azure.mgmt.web import WebSiteManagementClient

subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
myapp_base_url = "https://management.chinacloudapi.cn"

credentials = ClientSecretCredential(
    client_id=os.environ['AZURE_CLIENT_ID'],
    client_secret=os.environ['AZURE_CLIENT_SECRET'],
    tenant_id=os.environ['AZURE_TENANT_ID'],
    authority=AzureAuthorityHosts.AZURE_CHINA
)

def print_item(group):
    """Print some properties of an Azure model."""
    print("\tName: {}".format(group.name))
    print("\tId: {}".format(group.id))
    print("\tLocation: {}".format(group.location))
    print("\tTags: {}".format(group.tags))
    if hasattr(group, 'status'):
        print("\tStatus: {}".format(group.status))
    if hasattr(group, 'state'):  # Site
        print("\tStatus: {}".format(group.state))
    if hasattr(group, 'properties'):
        print_properties(group.properties)
    print("\n\n")

def print_properties(props):
    """Print some properties of a Site."""
    if props and props.provisioning_state:
        print("\tProperties:")
        print("\t\tProvisioning State: {}".format(props.provisioning_state))

def print_ipsecurityrestrictions(iprestrictions):
    """Print ip security restrictions of a Site."""
    for restrits in iprestrictions:
        print("\t for rule : {}".format(restrits.name))
        print("\t\t name : {}".format(restrits.name))
        print("\t\t ip_address : {}".format(restrits.ip_address))
        print("\t\t subnet_mask : {}".format(restrits.subnet_mask))
        print("\t\t action : {}".format(restrits.action))
        print("\t\t vnet_subnet_resource_id : {}".format(restrits.vnet_subnet_resource_id))
        print("\t\t vnet_traffic_tag : {}".format(restrits.vnet_traffic_tag))
        print("\t\t subnet_traffic_tag : {}".format(restrits.subnet_traffic_tag))
        print("\t\t tag : {}".format(restrits.tag))
        print("\t\t priority : {}".format(restrits.priority))
        print("\t\t description : {}".format(restrits.description))
        print("\n\n")

web_client = WebSiteManagementClient(credentials, subscription_id, base_url=myapp_base_url, credential_scopes=[
                                      AZURE_CHINA_CLOUD.endpoints.management + "/.default"])

resource_group_name = "app-rg"

for site in web_client.web_apps.list_by_resource_group(resource_group_name):
    print_item(site)
print("\n\n")
print("\nStart to get web app configs")

site_name = "testwebapp04"
configs = web_client.web_apps.get_configuration(resource_group_name, site_name)
print_ipsecurityrestrictions(configs.ip_security_restrictions)

#web_client.web_apps.create_or_update_configuration()

执行结果为:

 

 

附录一: 调试Ptyhon代码时,遇上了奇怪的AAD错误  azure.core.exceptions.ClientAuthenticationError: Authentication failed: AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope . . . / / / : a a a a a c c c d d e e e f g h h i i l l m m n n n n o p p s t t t t u u is not valid.

最后通过换一台执行代码的虚拟机后,同样的代码没有报错。所以最终定位到是本机环境中,给中azure identity 的包不一致导致。通过 pip -m list出两个环境不一样的module版本后,再本地重新安装azure identity 和 azure core 两个包后,问题消失!

azure-identity == 1.11.0
azure-core == 1.24.2 #1.25.1

 

参考资料

Manage Azure websites with Python : https://github.com/Azure-Samples/app-service-web-python-manage

 

 

与【Azure 应用服务】使用Python Azure SDK 来获取 App Service的访问限制信息(Access Restrictions) 相似的内容:

【Azure 应用服务】使用Python Azure SDK 来获取 App Service的访问限制信息(Access Restrictions)

azure.core.exceptions.ClientAuthenticationError: Authentication failed: AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is

【Azure 应用服务】调用Azure REST API来获取 App Service的访问限制信息(Access Restrictions)以及修改

问题描述 昨天的博文中(https://www.cnblogs.com/lulight/p/17099179.html)介绍了使用Python SDK 来获取App Service的访问限制信息,那么如何调用REST API来实现呢? 问题解答 如大家所知,Azure 不管是SDK, 门户UI,或者

在GPT-4时代使用Semantic Kernel构建AI Copilot问答 以及 Semantic Kernel文档更新

Semantic Kernel是一个开源SDK,可让您轻松地将OpenAI,Azure OpenAI和Hugging Face等AI服务与C#和Python等传统编程语言相结合。通过这样做,您可以创建结合两全其美的 AI 应用程序。 Semantic Kernel 团队在博客上发布了2篇文章:Sem

【Azure 应用服务】Azure Function Python函数部署到Azure后遇见 Value cannot be null. (Parameter 'receiverConnectionString') 错误

问题描述 使用VS Code创建Python Function,处理Event Hub中的数据。当部署到Azure Function App后,函数无法执行,查看 Function 日志出现 Value cannot be null. (Parameter 'receiverConnectionSt

【Azure 应用服务】Python fastapi Function在Azure中遇见AttributeError异常(AttributeError: 'AsgiMiddleware' object has no attribute 'handle_async')

问题描述 参考文档“Using FastAPI Framework with Azure Functions”, 使用FastAPI 模块在Function中实现API请求。通过VS Code本地运行成功。 但是部署到Azure Function App后,遇见了如下错误: [2023-01-30T

【Azure 应用服务】使用Docker Compose创建App Service遇见"Linux Version is too long. It cannot be more than 4000 characters"错误

{ "code":"DeploymentFailed", "message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-deployment-operations for usag

【Azure 应用服务】应用代码中需要使用客户端证书访问服务接口,部署在应用服务后报错不能找到证书(Cannot find the X.509 certificate)

问题描述 在应用中,需要访问另一个服务接口,这个接口需要使用客户端证书进行认证。在代码中使用 System.Security.Cryptography.X509Certificates 加载Window系统中 Current User\My 下的证书。 然后把证书通过App Service门户页面上

【Azure 应用服务】Java ODBC代码中,启用 Managed Identity 登录 SQL Server 报错 Managed Identity authentication is not available

问题描述 在App Service中启用Identity后,使用系统自动生成 Identity。 使用如下代码连接数据库 SQL Server: SQLServerDataSource dataSource = new SQLServerDataSource(); dataSource.setSer

【Azure 应用服务】App Service 默认页面暴露Tomcat版本信息,存在安全风险

问题描述 在创建Azure App Service时,服务端的配置使用Java 8 + Tomcat 8.5。默认的根目录页面显示出App Service Tomcat版本信息,存在一定的安全隐患。 如何来避免这个问题呢? 问题解答 因为在初始创建App Service时,Azure会根据所选Sta

【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数

问题描述 在Azure App Service for Windows的环境中,部署.NET应用,其中使用了 SAP NetWeaver RFC函数 (需要加载 sapnwrfc.dll)。详细的错误为: “System.DllNotFoundException: Unable to load DL