【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

 

 

相关文章
|
4天前
|
SQL 自然语言处理 数据库
【Azure Developer】分享两段Python代码处理表格(CSV格式)数据 : 根据每列的内容生成SQL语句
本文介绍了使用Python Pandas处理数据收集任务中格式不统一的问题。针对两种情况:服务名对应多人拥有状态(1/0表示),以及服务名与人名重复列的情况,分别采用双层for循环和字典数据结构实现数据转换,最终生成Name对应的Services列表(逗号分隔)。此方法高效解决大量数据的人工处理难题,减少错误并提升效率。文中附带代码示例及执行结果截图,便于理解和实践。
|
13天前
|
API 开发工具 Python
|
1月前
|
数据采集 供应链 API
实战指南:通过1688开放平台API获取商品详情数据(附Python代码及避坑指南)
1688作为国内最大的B2B供应链平台,其API为企业提供合法合规的JSON数据源,直接获取批发价、SKU库存等核心数据。相比爬虫方案,官方API避免了反爬严格、数据缺失和法律风险等问题。企业接入1688商品API需完成资质认证、创建应用、签名机制解析及调用接口四步。应用场景包括智能采购系统、供应商评估模型和跨境选品分析。提供高频问题解决方案及安全合规实践,确保数据安全与合法使用。立即访问1688开放平台,解锁B2B数据宝藏!
|
1月前
|
API 开发工具 Python
【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
本文介绍如何使用Python SDK为中国区微软云(China Azure)中的虚拟机磁盘创建快照。通过Azure Python SDK的Snapshot Class,指定`location`和`creation_data`参数,使用`Copy`选项从现有磁盘创建快照。代码示例展示了如何配置Default Azure Credential,并设置特定于中国区Azure的`base_url`和`credential_scopes`。参考资料包括官方文档和相关API说明。
|
2月前
|
存储 缓存 Java
Python高性能编程:五种核心优化技术的原理与Python代码
Python在高性能应用场景中常因执行速度不及C、C++等编译型语言而受质疑,但通过合理利用标准库的优化特性,如`__slots__`机制、列表推导式、`@lru_cache`装饰器和生成器等,可以显著提升代码效率。本文详细介绍了这些实用的性能优化技术,帮助开发者在不牺牲代码质量的前提下提高程序性能。实验数据表明,这些优化方法能在内存使用和计算效率方面带来显著改进,适用于大规模数据处理、递归计算等场景。
92 5
Python高性能编程:五种核心优化技术的原理与Python代码
|
3月前
|
Python
课程设计项目之基于Python实现围棋游戏代码
游戏进去默认为九路玩法,当然也可以选择十三路或是十九路玩法 使用pycharam打开项目,pip安装模块并引用,然后运行即可, 代码每行都有详细的注释,可以做课程设计或者毕业设计项目参考
92 33
|
22天前
|
机器学习/深度学习 存储 设计模式
Python 高级编程与实战:深入理解性能优化与调试技巧
本文深入探讨了Python的性能优化与调试技巧,涵盖profiling、caching、Cython等优化工具,以及pdb、logging、assert等调试方法。通过实战项目,如优化斐波那契数列计算和调试Web应用,帮助读者掌握这些技术,提升编程效率。附有进一步学习资源,助力读者深入学习。
|
22天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python 高级编程与实战:深入理解数据科学与机器学习
本文深入探讨了Python在数据科学与机器学习中的应用,介绍了pandas、numpy、matplotlib等数据科学工具,以及scikit-learn、tensorflow、keras等机器学习库。通过实战项目,如数据可视化和鸢尾花数据集分类,帮助读者掌握这些技术。最后提供了进一步学习资源,助力提升Python编程技能。
|
10天前
|
Python
[oeasy]python074_ai辅助编程_水果程序_fruits_apple_banana_加法_python之禅
本文回顾了从模块导入变量和函数的方法,并通过一个求和程序实例,讲解了Python中输入处理、类型转换及异常处理的应用。重点分析了“明了胜于晦涩”(Explicit is better than implicit)的Python之禅理念,强调代码应清晰明确。最后总结了加法运算程序的实现过程,并预告后续内容将深入探讨变量类型的隐式与显式问题。附有相关资源链接供进一步学习。
23 4
|
22天前
|
设计模式 机器学习/深度学习 前端开发
Python 高级编程与实战:深入理解设计模式与软件架构
本文深入探讨了Python中的设计模式与软件架构,涵盖单例、工厂、观察者模式及MVC、微服务架构,并通过实战项目如插件系统和Web应用帮助读者掌握这些技术。文章提供了代码示例,便于理解和实践。最后推荐了进一步学习的资源,助力提升Python编程技能。