如何使用 Python 检查虚拟机是否正在运行

我正在编写一个 python 运行手册,以便能够启动或停止虚拟机。如果虚拟机正在运行,我想停止它。如果它没有运行,我想打开它。我需要编写一个 if 条件来执行此操作,但我不知道如何在 azure 中获取我的虚拟机的状态,以便进行比较。


我尝试使用以下内容:


compute_client.virtual_machines.get(resourceGroupName, vmName, expand = 'instanceview')

但是当我打印这个时,我看不到如何访问虚拟机的状态。


这是我的脚本代码:


import os

from azure.mgmt.compute import ComputeManagementClient

import azure.mgmt.resource

import automationassets


import sys


resourceGroupName = str(sys.argv[1])

vmName = str(sys.argv[2])


def get_automation_runas_credential(runas_connection):

    from OpenSSL import crypto

    import binascii

    from msrestazure import azure_active_directory

    import adal


    # Get the Azure Automation RunAs service principal certificate

    cert = automationassets.get_automation_certificate("AzureRunAsCertificate")

    pks12_cert = crypto.load_pkcs12(cert)

    pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())


    # Get run as connection information for the Azure Automation service principal

    application_id = runas_connection["ApplicationId"]

    thumbprint = runas_connection["CertificateThumbprint"]

    tenant_id = runas_connection["TenantId"]


    # Authenticate with service principal certificate

    resource ="https://management.core.windows.net/"

    authority_url = ("https://login.microsoftonline.com/"+tenant_id)

    context = adal.AuthenticationContext(authority_url)

    return azure_active_directory.AdalAuthentication(

    lambda: context.acquire_token_with_client_certificate(

            resource,

            application_id,

            pem_pkey,

            thumbprint)

    )


# Authenticate to Azure using the Azure Automation RunAs service principal

runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")

azure_credential = get_automation_runas_credential(runas_connection)


# Initialize the compute management client with the RunAs credential and specify the subscription to work against.

compute_client = ComputeManagementClient(

    azure_credential,

    str(runas_connection["SubscriptionId"])

)


守着星空守着你
浏览 352回答 1
1回答

繁星淼淼

您使用的 Azure SDKazure.mgmt.compute是正确的。您只需要获取该信息中的 VM 状态即可。下面的代码:vm = compute_client.virtual_machines.get('v-chaxu-ChinaCXPTeam', 'azureUbuntu18', expand='instanceView')# These are the statuses of the VM about the event execution status and the vm state, the vm state is the second one.statuses = vm.instance_view.statusesprint(statuses[1].display_status)这里的输出:更多详细信息,请参见VM 信息中的 instance_view。或者也可以直接获取instance_view,代码如下:instance_view = compute_client.virtual_machines.instance_view('v-chaxu-ChinaCXPTeam', 'azureUbuntu18')print(instance_view.statuses[1].display_status)输出也和上面一样。有关更多详细信息,请参阅函数instance_view(resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python