zoukankan      html  css  js  c++  java
  • 腾讯云创建虚拟机

    # -*- 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)
    

      

  • 相关阅读:
    python zip()与zip(*ziped)以及list(zip(a,b))
    通信原理(第七版)-樊昌信-第一章-绪论-重要知识点
    通信原理-自相关与互相关函数的关系
    通信原理(第七版)-樊昌信-第二章-确知信号-重要知识点
    C#Linq的10个练习
    C#从委托、lambda表达式到linq总结
    C#的隐式类型、匿名类型、自动属性、初始化器
    MVC开发之Razor的使用
    Markdown常用语法
    MVC开发之注入容器Ninject的使用
  • 原文地址:https://www.cnblogs.com/slqt/p/10910196.html
Copyright © 2011-2022 走看看