使用Python API在Azure上获取虚拟机创建时间

时间:2017-10-13 00:10:39

标签: python python-2.7 azure azure-monitoring azure-sdk-python

我的要求是在启动(创建)时间内获取订阅中的所有VM。我没有在仪表板中找到VM创建的时间,就像在Activity log中找到了时间戳一样。我想获取由一个订阅ID创建的所有VM以及创建的时间。

(对于此帐户的详细信息,2FA已启用,因此UserPassCredentials 无法正常工作)

订阅ID中所有虚拟机的列表:

import os
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
compute_client = ComputeManagementClient(credentials, subscription_id)
for vm in compute_client.virtual_machines.list_all():
    print("\tVM: {}".format(vm.name)) 

Activity log获取已创建的时间:

import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'test-group'" ])
subscription_id = 'xxxxx'
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
client = MonitorClient(credentials, subscription_id)
select = ",".join([ "Administrative", "Write VirtualMachines" ]) 
activity_logs = client.activity_logs.list( filter=filter, select=select )

for i in activity_logs:
    pprint(i.__dict__) 

我能够获取所有虚拟机(第一个示例程序),但是在尝试获取Activity log时会出现一些错误(第二个示例程序)。

错误:

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 109, in __next__
    self.advance_page()
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "/Library/Python/2.7/site-packages/azure/monitor/operations/activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

有人可以帮我找到问题吗?任何帮助真的很感激。

2 个答案:

答案 0 :(得分:1)

我今天尝试使用您提供的代码获取我的资源组的活动日志,然后重现您的问题。

我的代码

import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

subscription_id = '***'
client_id='***'
secret='***'
tenant='***'

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant)

client = MonitorClient(credentials, subscription_id)
select = ",".join([ "eventName", "operationName" ])

print select
print filter
activity_logs = client.activity_logs.list( filter=filter, select=select )

for log in activity_logs:
    # assert isinstance(log, azure.monitor.models.EventData)
    print(" ".join([
        log.event_name.localized_value,
        log.operation_name.localized_value
    ]))

运行结果:

eventName,operationName
eventTimestamp le '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
Traceback (most recent call last):
  File "E:/PythonWorkSpace/ActiveLog/FetchActiveLog.py", line 24, in <module>
    for log in activity_logs:
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 109, in __next__
    self.advance_page()
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "E:\Python27\lib\site-packages\azure\monitor\operations\activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

重新评估Azure Monitor Python SDK后,我发现了差异。

filter = " and ".join([ "eventTimestamp ge '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

以下是ge,而不是le

我修改了关键字,然后代码适合我。

eventName,operationName
eventTimestamp ge '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
Begin request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/deallocate/action
Begin request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Compute/disks/write
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Network/networkSecurityGroups/write
End request Microsoft.Network/networkInterfaces/write
End request Microsoft.Network/publicIPAddresses/write

希望它对你有所帮助。

答案 1 :(得分:0)

根据文档,您的日期似乎应该被转义。而且,似乎他们需要一个日期时间(而不是日期): https://docs.microsoft.com/en-us/rest/api/monitor/activitylogs

filter = " and ".join([
        "eventTimestamp le '{}T00:00:00Z'".format(today),
        "resourceGroupName eq 'test-group'"
])