gpt4 book ai didi

azure - 使用python sdk获取azure中虚拟机的CPU利用率

转载 作者:行者123 更新时间:2023-12-02 08:01:57 24 4
gpt4 key购买 nike

我正在尝试使用 azure python API 获取虚拟机的 CPU 利用率。就像如果虚拟机有 2 个 cpu,我需要整体利用率(意味着 cpu1+ cpu2)。

获取虚拟机 CPU 利用率的可能方法有哪些?

最佳答案

您可能可以使用适用于 Python 的 Azure 监控库来获取 Azure VM 上的CPU 百分比指标。安装azure-mgmt-monitor包并调用MetricsOperations class中的list方法

Example - Metrics

import datetime
from azure.mgmt.monitor import MonitorManagementClient

# Get the ARM id of your resource. You might chose to do a "get"
# using the according management or to build the URL directly
# Example for a ARM VM
resource_id = (
"subscriptions/{}/"
"resourceGroups/{}/"
"providers/Microsoft.Compute/virtualMachines/{}"
).format(subscription_id, resource_group_name, vm_name)

# create client
client = MonitorManagementClient(
credentials,
subscription_id
)

# You can get the available metrics of this specific resource
for metric in client.metric_definitions.list(resource_id):
# azure.monitor.models.MetricDefinition
print("{}: id={}, unit={}".format(
metric.name.localized_value,
metric.name.value,
metric.unit
))

# Example of result for a VM:
# Percentage CPU: id=Percentage CPU, unit=Unit.percent
# Network In: id=Network In, unit=Unit.bytes
# Network Out: id=Network Out, unit=Unit.bytes
# Disk Read Bytes: id=Disk Read Bytes, unit=Unit.bytes
# Disk Write Bytes: id=Disk Write Bytes, unit=Unit.bytes
# Disk Read Operations/Sec: id=Disk Read Operations/Sec, unit=Unit.count_per_second
# Disk Write Operations/Sec: id=Disk Write Operations/Sec, unit=Unit.count_per_second

# Get CPU total of yesterday for this VM, by hour

today = datetime.datetime.now().date()
yesterday = today - datetime.timedelta(days=1)

metrics_data = client.metrics.list(
resource_id,
timespan="{}/{}".format(yesterday, today),
interval='PT1H',
metric='Percentage CPU',
aggregation='Total'
)

for item in metrics_data.value:
# azure.mgmt.monitor.models.Metric
print("{} ({})".format(item.name.localized_value, item.unit.name))
for timeserie in item.timeseries:
for data in timeserie.data:
# azure.mgmt.monitor.models.MetricData
print("{}: {}".format(data.time_stamp, data.total))

# Example of result:
# Percentage CPU (percent)
# 2016-11-16 00:00:00+00:00: 72.0
# 2016-11-16 01:00:00+00:00: 90.59
# 2016-11-16 02:00:00+00:00: 60.58
# 2016-11-16 03:00:00+00:00: 65.78
# 2016-11-16 04:00:00+00:00: 43.96
# 2016-11-16 05:00:00+00:00: 43.96
# 2016-11-16 06:00:00+00:00: 114.9
# 2016-11-16 07:00:00+00:00: 45.4

关于azure - 使用python sdk获取azure中虚拟机的CPU利用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com