首页 > 编程语言 >【Azure Developer】使用Python代码获取VM的IP地址 (Public IP + Private IP)

【Azure Developer】使用Python代码获取VM的IP地址 (Public IP + Private IP)

时间:2022-10-01 17:00:09浏览次数:82  
标签:run Users Python IP py File IP地址 azure line

记录使用以下的代码获取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​

 

 

 

@2022-10-01, 还没有解决它。

标签:run,Users,Python,IP,py,File,IP地址,azure,line
From: https://blog.51cto.com/u_13773780/5728294

相关文章

  • 【Azure Developer】使用Python代码获取VM的IP地址 (Public IP + Private IP)
     记录使用以下的代码获取AzureVM中的IP地址"""Createandmanagevirtualmachines.Thisscriptexpectsthatthefollowingenvironmentvarsareset:AZURE_......
  • Windows10 WSL子系统安装CentOS7、OpenSSL-3.0.5 及 Python-3.10.7
    本文版权归博主 惊梦无痕 所有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作。原文地址Linux小白一个,最近打算在Linux环境中学习Python,但又不想安装双系统,最后......
  • 【yaml】python解析yaml的 None类型
    1、问题做接口测试自动化时,参数传递时,默认给的null,直接写None会被解析成字符串  2、出问题的格式 打印“Total':'None' 3、正确的解析成None的方法方式一,......
  • python框架中自定义封装logging,一文解决
     为什么需要Logger刚开始写代码可能使用print打印输出就够用了,但是print重定向输出内容非常麻烦,而且无法区分打印日志等级。而logging可以设置打印等级,也可以重定向输......
  • 【python】Error:'int' object is not callable
    1、问题rpc接口在调用的时候报错   2、原因这个报错的意思就是int转换时,转换的对象不能调用本次错误,主要是因为int(obj.a)写成了int(obj.a()),导致属性获取失败......
  • 肖sir___第二个月Javascript_04
    1.1JavaScript简介JavaScript是互联网上最流行的脚本语言,这门语言可用于HTML和web,更可广泛用于服务器、PC、笔记本电脑、平板电脑和智能手机等设备JavaScript是......
  • Python爬虫--Requests 库用法大全
    昨晚分享了Python爬虫的基本知识,本文分享一下爬虫里面请求相关的内容:Requests用法。往期知识回顾:​​Python爬虫基本原理​​​​12.奇怪知识(1)--Matlab爬虫获取王者荣耀......
  • Python爬虫基本原理
    1、爬虫是什么爬虫是模拟用户在浏览器或者某个应用上的操作,把操作的过程、实现自动化的程序。当我们在浏览器中输入一个url后回车,后台会发生什么?比如说输入http://www.sina.......
  • javascript:每次只加载3个页面的幻灯(chrome 105.0.5195.125)
    一,js代码:<html><head><metacharset="utf-8"/><title>测试</title><scriptsrc="pcpageapp.js"></script><styletype="text/css">.page......
  • python截取字符串(字符串切片)
    python中使用[]来截取字符串,语法:字符串[起始位置:结束位置]一、起始位置:结束位置先看几个例子:s='python'print(s)#输出python直接输出字符串#从前......