Azure REST API (4) 在Python環境下,使用Azure REST API


  《Windows Azure Platform 系列文章目錄

 

  之前遇到的項目中,客戶需要在Python環境下,監控Azure VM的CPU利用率,在這里簡單記錄一下。

 

  筆者的環境是Windows 10,如果需要Python開發,首先需要准備以下環境:

  1.安裝Python,下載地址:https://www.python.org/downloads/,我這里分別安裝了Python 2.7.15和Python 3.7.0

  2.安裝PyCharm,下載地址:https://www.jetbrains.com/pycharm/download/#section=windows

  選擇導入開發環境配置文件,我們選擇不導入。

  3.配置PyCharm,我們配置運行環境:

  

 

  4.因為筆者用的是Azure China服務,我們在上圖中,需要增加相應的package。我們查詢到package名字為mcazurerm

  

 

  5.然后對mcazurerm進行配置,我們點擊External Libraries,Site-packages,mcazurerm,然后點擊settings.py

  增加SNAPSHOT_API = '2016-04-30-preview'。如下圖:

  

 

  6.獲得azure tenant id, appid, app secret, 訂閱id,資源組名稱,虛擬機名稱。具體可以參考之前的內容:

  https://www.cnblogs.com/threestone/p/9343146.html

 

  7.vmlist.py的代碼如下,分別實現了2個方法,list VM和獲得CPU利用率。

#!/usr/bin/env python
# -*- coding:utf8 -*-
import xdrlib ,sys
import xlrd
import mcazurerm
import json
import mcazurerm.restfns
#from restfns import do_delete, do_get, do_get_next, do_patch, do_post, do_put
#from settings import azure_rm_endpoint, SNAPSHOT_API
#from adalfns import get_access_token
import datetime

tenant_id = '這里輸入tenantid'
app_id = '這里輸入appid'
app_secret = '這里輸入appsecret'

subscription_id = '這里輸入訂閱ID'

location = 'chinaeast'
rg = '這里輸入資源組名稱'
vmname = '這里輸入Azure RM機器名'
vmname2= '這里輸入另外要監控的機器名'


newapiversion='2016-09-01'
# create an authentication token
access_token = mcazurerm.get_access_token(
    tenant_id,
    app_id,
    app_secret
)

def listvm(access_token, subscription_id, resource_group):
    endpoint = ''.join([mcazurerm.settings.azure_rm_endpoint,
                '/subscriptions/', subscription_id,
                '/resourceGroups/', resource_group,
                '/providers/Microsoft.Compute/virtualMachines',
                '?api-version=', mcazurerm.settings.SNAPSHOT_API])
    return mcazurerm.restfns.do_get(endpoint,access_token)



def GetCPU(access_toke,subscription_id,resource_group):
    endpoint = "".join([mcazurerm.settings.azure_rm_endpoint,
                "/subscriptions/", subscription_id,
                "/resourceGroups/", resource_group,
                "/providers/Microsoft.Compute/virtualMachines/",vmname,
                "/providers/microsoft.insights/metrics"
                "?$filter=(name.value eq 'Percentage CPU') and timeGrain eq duration'PT1M'",
                " and startTime eq 2018-08-22T08:19:26.2644638Z and endTime eq 2018-08-23T08:19:29.0454921Z",
                "&api-version=",newapiversion
                 ])

    print(endpoint)
    return mcazurerm.restfns.do_get(endpoint,access_token)

def GetNetworkIn(access_toke,subscription_id,resource_group):
    endpoint = "".join([mcazurerm.settings.azure_rm_endpoint,
                "/subscriptions/", subscription_id,
                "/resourceGroups/", resource_group,
                "/providers/Microsoft.Compute/virtualMachines/",vmname,
                "/providers/microsoft.insights/metrics"
                "?$filter=(name.value eq 'Network In') and timeGrain eq duration'PT1M'",
                " and startTime eq 2018-08-22T08:19:26.2644638Z and endTime eq 2018-08-23T08:19:29.0454921Z",
                "&api-version=",newapiversion
                 ])

    return mcazurerm.restfns.do_get(endpoint,access_token)

#https://docs.microsoft.com/en-us/rest/api/monitor/activitylogs/list#get_activity_logs_with_filter_and_select

#By reource group
def GetOperationByResourceGroup(access_toke,subscription_id,resource_group):
    endpoint = "".join([mcazurerm.settings.azure_rm_endpoint,
                "/subscriptions/", subscription_id,
                "/providers/microsoft.insights/eventtypes/management/values",
                "?api-version=", newapiversion,
                "&$filter=eventTimestamp ge '2018-08-01T20:00:00Z' and eventTimestamp le '2018-08-23T20:00:00Z' and resourceGroupName eq '",rg,
                "'"        ])
    return mcazurerm.restfns.do_get(endpoint,access_token)


#by resource URI
resourceuri="".join(["/subscriptions/",subscription_id ,"/resourceGroups/",rg,
                     "/providers/Microsoft.Compute/VirtualMachines/",vmname2])

def GetOperationByResourceURI(access_toke,subscription_id,resource_group):
    endpoint = "".join([mcazurerm.settings.azure_rm_endpoint,
                "/subscriptions/", subscription_id,
                "/providers/microsoft.insights/eventtypes/management/values",
                "?api-version=", newapiversion,
                "&$filter=eventTimestamp ge '2018-08-01T20:00:00Z' and eventTimestamp le '2018-08-23T20:00:00Z' and resourceUri eq '",resourceuri,
                "'"  ])
    return mcazurerm.restfns.do_get(endpoint,access_token)


vmlistreturn1 = listvm(access_token,subscription_id,rg)
vmlistreturn2 = GetCPU(access_token,subscription_id,rg)

vmlistreturn3 = GetNetworkIn(access_token,subscription_id,rg)
vmlistreturn4 = GetOperationByResourceGroup(access_token,subscription_id,rg)
vmlistreturn5 = GetOperationByResourceURI(access_token,subscription_id,rg)

print(vmlistreturn2)
print(vmlistreturn3)
print(vmlistreturn4)
print(vmlistreturn5)

 

 

  8.其他REST API,可以參考Azure MSDN文檔:

  https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines

  https://docs.microsoft.com/en-us/rest/api/monitor/activitylogs/list#get_activity_logs_with_filter_and_select

 

 

  9.另外如果需要監控Azure China CDN流量的話,請參考下面的內容。我們點擊下圖的CDN Manage

  

 

  10.在彈出的窗口中,找到安全管理,秘鑰管理。如下圖:

  

 

  11.點擊創建秘鑰,如下圖:

  

 

  12.獲取到秘鑰的ID和Key

  

 

  13.在Python中,增加如下代碼:

cdnsubscription_id = 'CDN所在的訂閱ID'
cdnendpoint_id='CDN上面的Endpoint ID,具體的返回方法請參考下面的步驟'

apiversion='1.0'
cdnkeyid='輸入上面步驟的cdnkeyid'
cdnkeyvalue='輸入上面步驟的cdnkey value'

def calculate_authorization_header(request_url, request_time, key_id, key_value, http_method):
    """ Calculate the authorization header.
    @request_url: Complete request URL with scheme, host, path and queries
    @request_time: UTC request time with format yyyy-MM-dd hh:mm:ss
    @key_id: API key ID
    @key_value: API key value
    @http_method: Http method in upper case

    """
    urlparts = urlparse.urlparse(request_url)
    queries = urlparse.parse_qs(urlparts.query)
    ordered_queries = collections.OrderedDict(sorted(queries.items()))
    message = "%s\r\n%s\r\n%s\r\n%s" % (urlparts.path, ", ".join(['%s:%s' % (key, value[0]) for (key, value) in ordered_queries.items()]), request_time, http_method)
    digest = hmac.new(bytearray(key_value, "utf-8"), bytearray(message, "utf-8"), hashlib.sha256).hexdigest().upper()
    return "AzureCDN %s:%s" % (key_id, digest)


requesturl= "".join(["https://restapi.cdn.azure.cn/subscriptions/", cdnsubscription_id,
                "/endpoints?apiVersion=",apiversion
                    ])
currentUTCTime = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
CDNheader = calculate_authorization_header(requesturl,currentUTCTime,cdnkeyid,cdnkeyvalue,'GET')

#這個接口 返回CDN Endpoint ID
CDNlist= mcazurerm.restfns.do_CDNget(requesturl,currentUTCTime,CDNheader)


#https://docs.azure.cn/zh-cn/cdn/cdn-api-get-subscription-volume
#startTime yyyy-MM-ddThh:mm:ssZ
#endTime  yyyy-MM-ddThh:mm:ssZ
#granularity PerFiveMinutes,PerHour,PerDay

requesturl= "".join(["https://restapi.cdn.azure.cn/subscriptions/", cdnsubscription_id,
                "/endpoints/",cdnendpoint_id,
                "/volume?apiVersion=",apiversion,
                "&startTime=2018-08-18T00:00:00Z&endTime=2018-08-20T06:32:53Z&granularity=PerHour"
                     ])

currentUTCTime = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
CDNheader = calculate_authorization_header(requesturl,currentUTCTime,cdnkeyid,cdnkeyvalue,'GET')
CDNlist= mcazurerm.restfns.do_CDNget(requesturl,currentUTCTime,CDNheader)

 

  14.修改restfns.py,增加方法:

def do_CDNget(endpoint, requestdate, access_token):
    headers = {
        "x-azurecdn-request-date": requestdate,
        "Authorization": access_token
               }
    return requests.get(endpoint, headers=headers).json()

 

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM