【Azure Developer】使用Python代码获取VM的IP地址 (Public IP + Private IP)【未解决问题标签】

简介: 【Azure Developer】使用Python代码获取VM的IP地址 (Public IP + Private IP)【未解决问题标签】

 

记录使用以下的代码获取Azure VM中的IP地址

"""Create and manage virtual machines.
 
This script expects that the following environment vars are set:
 
AZURE_TENANT_ID: your Azure Active Directory tenant id or domain
AZURE_CLIENT_ID: your Azure Active Directory Application Client ID
AZURE_CLIENT_SECRET: your Azure Active Directory Application Secret
AZURE_SUBSCRIPTION_ID: your Azure Subscription Id
"""
import os
import traceback
 
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.compute.models import DiskCreateOption
 
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_cloud import AZURE_CHINA_CLOUD
# from azure.identity import DefaultAzureCredential
# from azure.identity import ClientSecretCredential
# credentials = ClientSecretCredential(client_id='xxxxxxxx-xxxx-xxxx-xxxx-76f50363af33', client_secret='.~V9ij1.5Y_F8rL_k8DNpj~RSLFf~H56nH', tenant_id='xxxxxxxx-xxxx-xxxx-xxxx-1316152d9587',authority=AzureAuthorityHosts.AZURE_CHINA)
# token =credentials.get_token("https://microsoftgraph.chinacloudapi.cn/.default")
# print(token)
def get_credentials():
    subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
    print(subscription_id)
    credentials = ServicePrincipalCredentials(
        client_id=os.environ['AZURE_CLIENT_ID'],
        secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant=os.environ['AZURE_TENANT_ID'],
        resource="https://management.chinacloudapi.cn/",
        authority=AZURE_CHINA_CLOUD.endpoints.active_directory,
        scopes="https://management.chinacloudapi.cn/.default",
        china=True
    )
    # credentials = ClientSecretCredential(
    #     client_id=os.environ['AZURE_CLIENT_ID'],
    #     client_secret=os.environ['AZURE_CLIENT_SECRET'],
    #     tenant_id=os.environ['AZURE_TENANT_ID'],
    #     resource="https://management.chinacloudapi.cn/",
    #     authority=AZURE_CHINA_CLOUD.endpoints.active_directory,
    #     scopes="https://management.chinacloudapi.cn/.default",
    #     china=True
    # )
    return credentials, subscription_id
 
def run_example():
    """Virtual Machine management example."""
    #
   # Create all clients with an Application (service principal) token provider
    #
    credentials, subscription_id = get_credentials()
    #access_token = credentials.token['access_token']
    #print(access_token)
    # client2 = MonitorManagementClient(
    #     credential,
    #     subscription_id,
    #     base_url=CLOUD.endpoints.resource_manager,
    #     credential_scopes=[CLOUD.endpoints.resource_manager + "/.default"]
    # )
    resource_client = ResourceManagementClient(credentials, subscription_id,base_url="https://management.chinacloudapi.cn/",scopes="https://management.chinacloudapi.cn/.default")
    compute_client = ComputeManagementClient(credentials, subscription_id,base_url="https://management.chinacloudapi.cn/",scopes="https://management.chinacloudapi.cn/.default")
    network_client = NetworkManagementClient(credentials, subscription_id,base_url="https://management.chinacloudapi.cn/",scopes="https://management.chinacloudapi.cn/.default")
    print(AZURE_CHINA_CLOUD.endpoints.active_directory_resource_id)
    for public_ip in network_client.public_ip_addresses.list_all():
            print("Public IP: {}:{}".format(public_ip.id, public_ip.ip_address))
    for network_interface in network_client.network_interfaces.list_all():
        if (network_interface.virtual_machine != None):
            print("VM ID: " + network_interface.virtual_machine.id)
            for ip_configuration in network_interface.ip_configurations:
                if (ip_configuration.primary):
                    print("VM Used Public IP: " + ip_configuration.public_ip_address.id)
    try:
        # List VMs in subscription
        print('\nList VMs in subscription')
        for vm in compute_client.virtual_machines.list_all():
            print("\tVM: {}".format(vm))
 
    except CloudError:
        print('A VM operation failed:\n{}'.format(traceback.format_exc()))
    else:
        print('All example operations completed successfully!')
 
if __name__ == "__main__":
    run_example()

但是,结果却没有能成功。

遇见问题:

https://management.chinacloudapi.cn/.default
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
    cli.main()
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 321, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 135, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "c:\Users\.vscode\extensions\ms-python.python-2022.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 124, in _run_code
    exec(code, run_globals)
  File "c:\LBWorkSpace\MyCode\61-VM-Python\getIPaddress\getip.py", line 97, in <module>
    run_example()
  File "c:\LBWorkSpace\MyCode\61-VM-Python\getIPaddress\getip.py", line 75, in run_example
    for public_ip in network_client.public_ip_addresses.list_all():
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\paging.py", line 128, in __next__
    return next(self._page_iterator)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\mgmt\network\v2022_01_01\operations\_operations.py", line 32711, in get_next
    pipeline_response = self._client._pipeline.run(  # pylint: disable=protected-access
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\_base.py", line 211, in run
    return first_node.send(pipeline_request)  # type: ignore
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
    response = self.next.send(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
    response = self.next.send(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
    response = self.next.send(request)
  [Previous line repeated 2 more times]
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\mgmt\core\policies\_base.py", line 47, in send
    response = self.next.send(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\policies\_redirect.py", line 158, in send
    response = self.next.send(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\policies\_retry.py", line 446, in send
    response = self.next.send(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\policies\_authentication.py", line 119, in send
    self.on_request(request)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\core\pipeline\policies\_authentication.py", line 96, in on_request
    self._token = self._credential.get_token(*self._scopes)
AttributeError: 'ServicePrincipalCredentials' object has no attribute 'get_token'. Did you mean: 'set_token'?

通过Bing搜索查找,怀疑是packages中版本冲突引起。参考链接:

https://github.com/Azure/azure-sdk-for-python/issues/16908

https://github.com/Azure/azure-sdk-for-python/issues/14059

 

 

相关文章
|
1天前
|
缓存 开发者 Python
探索Python中的装饰器:简化和增强你的代码
【10月更文挑战第32天】 在编程的世界中,简洁和效率是永恒的追求。Python提供了一种强大工具——装饰器,它允许我们以声明式的方式修改函数的行为。本文将深入探讨装饰器的概念、用法及其在实际应用中的优势。通过实际代码示例,我们不仅理解装饰器的工作方式,还能学会如何自定义装饰器来满足特定需求。无论你是初学者还是有经验的开发者,这篇文章都将为你揭示装饰器的神秘面纱,并展示如何利用它们简化和增强你的代码库。
|
2天前
|
机器学习/深度学习 自然语言处理 API
如何使用阿里云的语音合成服务(TTS)将文本转换为语音?本文详细介绍了从注册账号、获取密钥到编写Python代码调用TTS服务的全过程
如何使用阿里云的语音合成服务(TTS)将文本转换为语音?本文详细介绍了从注册账号、获取密钥到编写Python代码调用TTS服务的全过程。通过简单的代码示例,展示如何将文本转换为自然流畅的语音,适用于有声阅读、智能客服等场景。
18 3
|
4天前
|
设计模式 缓存 测试技术
Python中的装饰器:功能增强与代码复用的艺术####
本文将深入探讨Python中装饰器的概念、用途及实现方式,通过实例演示其如何为函数或方法添加新功能而不影响原有代码结构,从而提升代码的可读性和可维护性。我们将从基础定义出发,逐步深入到高级应用,揭示装饰器在提高代码复用性方面的强大能力。 ####
|
2天前
|
算法 IDE API
Python编码规范与代码可读性提升策略####
本文探讨了Python编码规范的重要性,并深入分析了如何通过遵循PEP 8等标准来提高代码的可读性和可维护性。文章首先概述了Python编码规范的基本要求,包括命名约定、缩进风格、注释使用等,接着详细阐述了这些规范如何影响代码的理解和维护。此外,文章还提供了一些实用的技巧和建议,帮助开发者在日常开发中更好地应用这些规范,从而编写出更加清晰、简洁且易于理解的Python代码。 ####
|
5天前
|
缓存 测试技术 数据安全/隐私保护
探索Python中的装饰器:简化代码,增强功能
【10月更文挑战第29天】本文通过深入浅出的方式,探讨了Python装饰器的概念、使用场景和实现方法。文章不仅介绍了装饰器的基本知识,还通过实例展示了如何利用装饰器优化代码结构,提高代码的可读性和重用性。适合初学者和有一定经验的开发者阅读,旨在帮助读者更好地理解和应用装饰器,提升编程效率。
|
9天前
|
设计模式 开发者 Python
Python编程中的设计模式:工厂方法模式###
本文深入浅出地探讨了Python编程中的一种重要设计模式——工厂方法模式。通过具体案例和代码示例,我们将了解工厂方法模式的定义、应用场景、实现步骤以及其优势与潜在缺点。无论你是Python新手还是有经验的开发者,都能从本文中获得关于如何在实际项目中有效应用工厂方法模式的启发。 ###
|
2天前
|
存储 人工智能 数据挖掘
从零起步,揭秘Python编程如何带你从新手村迈向高手殿堂
【10月更文挑战第32天】Python,诞生于1991年的高级编程语言,以其简洁明了的语法成为众多程序员的入门首选。从基础的变量类型、控制流到列表、字典等数据结构,再到函数定义与调用及面向对象编程,Python提供了丰富的功能和强大的库支持,适用于Web开发、数据分析、人工智能等多个领域。学习Python不仅是掌握一门语言,更是加入一个充满活力的技术社区,开启探索未知世界的旅程。
11 5
|
2天前
|
人工智能 数据挖掘 开发者
探索Python编程:从基础到进阶
【10月更文挑战第32天】本文旨在通过浅显易懂的语言,带领读者从零开始学习Python编程。我们将一起探索Python的基础语法,了解如何编写简单的程序,并逐步深入到更复杂的编程概念。文章将通过实际的代码示例,帮助读者加深理解,并在结尾处提供练习题以巩固所学知识。无论你是编程新手还是希望提升编程技能的开发者,这篇文章都将为你的学习之旅提供宝贵的指导和启发。
|
14天前
|
弹性计算 安全 小程序
编程之美:Python让你领略浪漫星空下的流星雨奇观
这段代码使用 Python 的 `turtle` 库实现了一个流星雨动画。程序通过创建 `Meteor` 类来生成具有随机属性的流星,包括大小、颜色、位置和速度。在无限循环中,流星不断移动并重新绘制,营造出流星雨的效果。环境需求为 Python 3.11.4 和 PyCharm 2023.2.5。