zoukankan      html  css  js  c++  java
  • 金山云KEC查询开关机API实现代码(签名)

    # -*- coding:utf-8 -*-
    # AWS Version 4 signing example
    
    # EC2 API (DescribeRegions)
    
    # See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
    # This version makes a GET request and passes the signature
    # in the Authorization header.
    import sys, os, base64, datetime, hashlib, hmac 
    import requests # pip install requests
    
    access_key = 'xxxxxxxxxxxxxxxxxxxxxxxx'
    secret_key = 'SSSSSSSSSSSSSSSSSSSSSSSSSS'
    if access_key is None or secret_key is None:
        print ('No access key is available.')
        sys.exit()
    
    # ************* REQUEST VALUES *************
    method = 'GET'
    service = 'kec'
    host = 'kec.cn-beijing-6.api.ksyun.com'
    region = 'cn-beijing-6'
    endpoint = 'https://kec.cn-beijing-6.api.ksyun.com'
    
    request_parameters = 'Action=DescribeInstances&Version=2016-03-04' #查询主机
    
    body = ''
    # Key derivation functions. See:
    # http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
    def sign(key, msg):
        return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
    
    def getSignatureKey(key, dateStamp, regionName, serviceName):
        kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
        kRegion = sign(kDate, regionName)
        kService = sign(kRegion, serviceName)
        kSigning = sign(kService, 'aws4_request')
        return kSigning
    
    # Read AWS access key from env. variables or configuration file. Best practice is NOT
    # to embed credentials in code.
    #access_key = os.environ.get('AWS_ACCESS_KEY_ID')
    #secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
    
    # Create a date for headers and the credential string
    t = datetime.datetime.utcnow()
    amzdate = t.strftime('%Y%m%dT%H%M%SZ')
    datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
    
    
    # ************* TASK 1: CREATE A CANONICAL REQUEST *************
    # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
    
    # Step 1 is to define the verb (GET, POST, etc.)--already done.
    
    # Step 2: Create canonical URI--the part of the URI from domain to query 
    # string (use '/' if no path)
    canonical_uri = '/' 
    
    # Step 3: Create the canonical query string. In this example (a GET request),
    # request parameters are in the query string. Query string values must
    # be URL-encoded (space=%20). The parameters must be sorted by name.
    # For this example, the query string is pre-formatted in the request_parameters variable.
    canonical_querystring = request_parameters
    # Step 4: Create the canonical headers and signed headers. Header names
    # must be trimmed and lowercase, and sorted in code point order from
    # low to high. Note that there is a trailing 
    .
    canonical_headers = 'host:' + host + '
    ' + 'x-amz-date:' + amzdate + '
    '
    
    # Step 5: Create the list of signed headers. This lists the headers
    # in the canonical_headers list, delimited with ";" and in alpha order.
    # Note: The request can include any headers; canonical_headers and
    # signed_headers lists those that you want to be included in the 
    # hash of the request. "Host" and "x-amz-date" are always required.
    signed_headers = 'host;x-amz-date'
    # Step 6: Create payload hash (hash of the request body content). For GET
    # requests, the payload is an empty string ("").
    payload_hash = hashlib.sha256(body.encode()).hexdigest()
    #payload 指的是对body体的hash值
    
    # Step 7: Combine elements to create canonical request
    canonical_request = method + '
    ' + canonical_uri + '
    ' + canonical_querystring + '
    ' + canonical_headers + '
    ' + signed_headers + '
    ' + payload_hash
    print('33[32;1m 创建一个规范化请求字符串,如下33[0m')
    print(canonical_request)
    print('33[32;1m*****************签名字符串准备*******************************************33[0m')
    # ************* TASK 2: CREATE THE STRING TO SIGN*************
    # Match the algorithm to the hashing algorithm you use, either SHA-1 or
    # SHA-256 (recommended)
    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
    print('33[32;1m 证书范围字符串,如下33[0m')
    print(credential_scope)
    
    string_to_sign = algorithm + '
    ' +  amzdate + '
    ' +  credential_scope + '
    ' +  hashlib.sha256(canonical_request.encode()).hexdigest()
    print('33[32;1m用 签名算法 + 时间年月日 + (具体时间 region service + aws4_request 组成的证书范围) + 规范化请求字符串的哈希值 组合生成要签名的字符串如下33[0m
    ', string_to_sign)
    #
    # ************* TASK 3: CALCULATE THE SIGNATURE *************
    # Create the signing key using the function defined above.
    signing_key = getSignatureKey(secret_key, datestamp, region, service)
    print('33[32;1m使用  SK:%s 时间:%s region:%s service:%s 生成的签名键如下33[0m' %(secret_key,datestamp,region,service))
    print(signing_key)
    # Sign the string_to_sign using the signing_key
    print('33[32;1m 对字符串签名结果如下33[0m')
    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
    print(signature)
    
    # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
    # The signing information can be either in a query string value or in 
    # a header named Authorization. This code shows how to use a header.
    # Create authorization header and add to request headers
    authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
    
    print('33[32;1m 生成Authorization: 值如下33[0m',authorization_header)
    # The request can include any headers, but MUST include "host", "x-amz-date", 
    # and (for this scenario) "Authorization". "host" and "x-amz-date" must
    # be included in the canonical_headers and signed_headers, as noted
    # earlier. Order here is not significant.
    # Python note: The 'host' header is added automatically by the Python 'requests' library.
    headers = {'Content-Type':'application/json','X-Amz-Date':amzdate, 'Authorization':authorization_header}
    #print amzdate
    #print authorization_header
    #
    # ************* SEND THE REQUEST *************
    request_url = endpoint + '?' + canonical_querystring
    
    print('
    ###############开始请求##############')
    print('Request URL = ' + request_url)
    r = requests.get(request_url, headers=headers)
    
    print('
    ######################RESPONSE#######################')
    print('Response code: %d
    ' % r.status_code)
    print(r.text)
    #print r.connection,dir(r.connection)
    #print dir(r)
    aws签名查询主机
    # coding=utf-8
    __author__ = 'lyj'
    # 需要先安装导入包
    # pip install requests
    # pip install requests-aws4auth
    import requests
    from requests_aws4auth import AWS4Auth
    import logging
    import sys
    # import Queue
    import threading
    import time
    
    
    logger = logging.getLogger("mylogger")
    logger.setLevel("DEBUG")
    ch = logging.StreamHandler()
    ch.setLevel("DEBUG")
    logger.addHandler(ch)
    
    if __name__ == '__main__':
        logger.debug("开始开/关主机-----")
        region = 'cn-beijing-6'
        service = 'kec'
        host = 'http://%s.%s.api.ksyun.com' % (service, region)
        headers = {
            'Accept': 'Application/json'
        }
        #自己的ak/sk
        ak = "AKLTu6ms_h_4Qm-he7UnY3Koqw"
        sk = "OKXJonEQYvSWrY9/qSq4HRuNtlXZeUIjslPwgmDQe92RL1TzS5KHgCI4lMTJaN6t5A=="
        logger.debug("region:" + region +",service:" + service +",host:" + host+",ak:" + ak +",sk:" + sk)
        credentials = {
            'ak': ak,
            'sk': sk
        }
        auth = AWS4Auth(credentials['ak'], credentials['sk'], region, service)
    
        query = {
                'Action': 'RebootInstances',
                'Version': '2016-03-04',
                # 'ForceStop':'false',
                'InstanceId.1':'8f390eb8-9406-4be5-bd9e-ecc7e7c62902'
            }
        print(auth,dir(auth),'
    ',auth.signing_key,auth.regenerate_signing_key())
        response = requests.get(host, params=query, headers=headers, auth=auth)
        logger.debug(response.text)
    AWS 关闭/开启/重启主机
  • 相关阅读:
    剑指offer——最小的K个数和数组中第K大的元素
    Leetcode刷题指南链接整理
    160. Intersection of Two Linked Lists
    100. Same Tree
    92. Reverse Linked List II
    94. Binary Tree Inorder Traversal
    79. Word Search
    78,90,Subsets,46,47,Permutations,39,40 DFS 大合集
    0x16 Tire之最大的异或对
    0x16 Tire
  • 原文地址:https://www.cnblogs.com/zhangmingda/p/10126406.html
Copyright © 2011-2022 走看看