【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天前
|
SQL JavaScript 前端开发
基于Python访问Hive的pytest测试代码实现
根据《用Java、Python来开发Hive应用》一文,建立了使用Python、来开发Hive应用的方法,产生的代码如下
12 6
基于Python访问Hive的pytest测试代码实现
|
3天前
|
设计模式 缓存 开发者
Python中的装饰器:简化代码,提高可读性
【9月更文挑战第10天】在Python编程的世界中,装饰器是一种强大的工具,它允许开发者在不修改原函数代码的情况下增加额外的功能。本文将通过简单易懂的语言和生动的例子,带你了解装饰器的概念、使用方法及其在实际开发中的应用价值。我们将一起探索如何利用装饰器来简化代码结构,提升代码的可读性和可维护性,让你的编程之旅更加顺畅。
|
2天前
|
存储 安全 数据安全/隐私保护
安全升级!Python AES加密实战,为你的代码加上一层神秘保护罩
【9月更文挑战第12天】在软件开发中,数据安全至关重要。本文将深入探讨如何使用Python中的AES加密技术保护代码免受非法访问和篡改。AES(高级加密标准)因其高效性和灵活性,已成为全球最广泛使用的对称加密算法之一。通过实战演练,我们将展示如何利用pycryptodome库实现AES加密,包括生成密钥、初始化向量(IV)、加密和解密文本数据等步骤。此外,还将介绍密钥管理和IV随机性等安全注意事项。通过本文的学习,你将掌握使用AES加密保护敏感数据的方法,为代码增添坚实的安全屏障。
15 8
|
1天前
|
机器学习/深度学习 测试技术 数据处理
KAN专家混合模型在高性能时间序列预测中的应用:RMoK模型架构探析与Python代码实验
Kolmogorov-Arnold网络(KAN)作为一种多层感知器(MLP)的替代方案,为深度学习领域带来新可能。尽管初期测试显示KAN在时间序列预测中的表现不佳,近期提出的可逆KAN混合模型(RMoK)显著提升了其性能。RMoK结合了Wav-KAN、JacobiKAN和TaylorKAN等多种专家层,通过门控网络动态选择最适合的专家层,从而灵活应对各种时间序列模式。实验结果显示,RMoK在多个数据集上表现出色,尤其是在长期预测任务中。未来研究将进一步探索RMoK在不同领域的应用潜力及其与其他先进技术的结合。
13 4
|
4天前
|
开发者 Python
Python中的装饰器:简化你的代码
【9月更文挑战第9天】本文将介绍Python中的一种强大工具——装饰器。我们将从基础概念开始,逐步深入到装饰器的实际应用,包括函数装饰器和类装饰器。我们将通过实例来展示如何利用装饰器简化代码,提高代码的可读性和可维护性。最后,我们将探讨装饰器的一些高级用法,以及如何避免在使用时可能遇到的问题。无论你是初学者还是有经验的开发者,这篇文章都将帮助你更好地理解和使用装饰器。
14 6
|
3天前
|
存储 人工智能 数据挖掘
Python编程入门:从基础到实战
【9月更文挑战第10天】本文将引导你进入Python编程的世界,从基本语法到实际项目应用,逐步深入。我们将通过简单的例子和代码片段,帮助你理解并掌握Python编程的精髓。无论你是编程新手还是有一定经验的开发者,都能在这篇文章中找到有价值的信息。让我们一起开始Python编程之旅吧!
|
3天前
|
机器学习/深度学习 数据挖掘 开发者
探索Python编程:从基础到进阶的旅程
【9月更文挑战第10天】本文是一篇深入浅出的技术感悟文章,通过作者自身的学习经历,向读者展示了如何从Python编程的基础入门逐步深入到高级应用。文章不仅分享了实用的代码示例,还提供了学习资源和建议,旨在鼓励初学者坚持学习,不断探索编程世界的奥秘。
|
2天前
|
存储 开发者 索引
掌握Python编程:从基础到高级
【9月更文挑战第11天】本文将引导你进入Python编程的世界,无论你是初学者还是有经验的开发者。我们将从基础语法开始,逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。每个部分都将通过实际代码示例进行说明,帮助你更好地理解和应用所学知识。让我们一起探索Python的强大功能和灵活性,开启你的编程之旅!
|
4天前
|
存储 数据采集 人工智能
探索Python编程之美——从基础到进阶
【9月更文挑战第9天】本文是一篇深入浅出的技术分享文章,旨在引导读者从零基础开始掌握Python编程。我们将通过生动的实例和代码示例,探讨Python的基本语法、数据结构、函数、模块以及面向对象编程等核心概念。无论你是初学者还是有一定经验的开发者,都能在这篇文章中找到有价值的内容。让我们一起开启Python编程之旅吧!
18 11