• 腾讯云创建虚拟机


    # -*- coding: utf-8 -*-
    
    from tencentcloud.common import credential
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.cvm.v20170312 import cvm_client, models
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.profile.client_profile import ClientProfile
    import json
    import sys
    import requests, ssl
    import urllib, re, os
    import time
    
    ssl._create_default_https_context = ssl._create_unverified_context
    requests.packages.urllib3.disable_warnings()
    
    try:
        def get_config(which):
            values = {}
            # user_path = os.path.join(os.path.abspath('.'), 'conf', 'user.py')
            # coding: UTF-8
            import os
            from os.path import exists, join, basename, dirname, isdir
    
            file_dir = '/'.join(dirname(__file__).split(os.sep)[:-2])
            user_path = os.path.join(file_dir, 'conf', 'user.py')
            execfile(user_path, values)
            return values.get(which, None)
    
    
        def derypt(data):
            pre_url = get_config('ROOT_SERVER_URL')
            reip = re.compile(r'(http.*?//.*?/)')
            url = "{}:7550/daemon/api/v2/encryption/decrypt?encrypted_text={}".format(
                reip.findall(pre_url)[0].rstrip('/'), urllib.quote(data))
            res = requests.get(url)
            return res.content
    
    
        def get_value(data, key=None):
            if not data:
                print '参数不允许为空'
                sys.exit(1)
            data = json.loads(data)
            if isinstance(data[0], dict):
                if key:
                    return data[0][key]
                for k, v in data[0].items():
                    return v
            elif isinstance(data, str):
                return data
    
    
        secretId = get_value(secret_id)
        secretKey = get_value(secret_key)
        secretKey = derypt(secretKey)
    
        available_zone = get_value(available_zone)
        Zone = get_value(zone)
        ProjectId = get_value(project_id)
        image_id = get_value(image_id)
        endpoint = get_value(endpoint)
    
        ProjectId = 0
    
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = endpoint  # 指定接入地域域名(默认就近接入)
    
        # 实例化一个client选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.signMethod = "HmacSHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.httpProfile = httpProfile
    
        cred = credential.Credential(secretId, secretKey)
        client = cvm_client.CvmClient(cred, available_zone)
        #
        placement = {"ProjectId": ProjectId, "Zone": Zone}
    
        internetAccessible = {'InternetChargeType': 'TRAFFIC_POSTPAID_BY_HOUR',
                              'InternetMaxBandwidthOut': 5,  # 带宽上限,Mbps
                              'PublicIpAssigned': True
                              }
    
        loginsetings = {'Password': str(password)}
        #
        params = {'ImageId': image_id,
                  'Placement': placement,
                  'InternetAccessible': internetAccessible,
                  'LoginSettings': loginsetings,
                  'InstanceType': instance_type}
    
        print params
        resp = client.call('RunInstances', params)
        resp = json.loads(resp)
        try:
            vm_id = resp['Response']['InstanceIdSet'][0]
            print vm_id
            i=0
            req = models.DescribeInstancesStatusRequest()
            req.InstanceIds = [str(vm_id)]
            req.Offset =0
            req.Limit = 20
            while 1:
                resp = client.DescribeInstancesStatus(req)
                resp= resp.to_json_string()
                resp=json.loads(resp)
                time.sleep(3)
                status=resp["InstanceStatusSet"][0]["InstanceState"]
                if status=="RUNNING":
                    break
                if status !='PENDING':
                    print '虚拟机状态异常,目前状态为:',status
                    sys.exit(1)
    
            print '虚拟机创建成功,id为:', vm_id
        except:
            print '创建虚拟机失败,返回信息如下:'
            print resp
            sys.exit(1)
    except TencentCloudSDKException as err:
        print(err)
    

      

  • 相关阅读:
    Codeforces Round #603 (Div. 2) E. Editor(线段树)
    Codeforces Round #603 (Div. 2) D. Secret Passwords(并查集)
    Java的DAO设计模式
    js实现本地时间同步
    循环播放
    正则表达式(2)
    正则表达式(1)
    第十八个知识点:画一个描述ECB,CBC,CTR模式的操作
    第十七个知识点:描述和比较DES和AES的轮结构
    第四十一个知识点 所有的侧信道分析都是能量分析吗
  • 原文地址:https://www.cnblogs.com/slqt/p/10910196.html
Copyright © 2020-2023  润新知