金山云开发

安装sdk
import os
import zipfile
import commands
cmd='cd {};cd ksc-sdk-python-master;{} setup.py install'.format(dst_dir,python_path)
print cmd
res=commands.getstatusoutput(cmd)
if res[0]:
    print res
else:
    print '安装成功!'

  

创建虚拟机
#coding=utf8
from kscore.session import get_session
import re
import sys


def make_conn(service_name, region):
    try:
        s = get_session()
        url = 'http://kec.{}.XXX.XXXX'.format(region)
        if url.startswith('http://'):
            is_ssl = False
        else:
            is_ssl = True
        client = s.create_client(service_name, region_name=region, endpoint_url=url,
                                 use_ssl=is_ssl, ks_access_key_id=ACCESS_KEY_ID,
                                 ks_secret_access_key=SECRET_ACCESS_KEY, api_version='2016-03-04',
                                 verify=False)
        return client
    except Exception as e:
        print e


def create_vm(client,instance_type='I1.1A',password=None,image_id=None,subnet_id=None,
              security_group_id=None,vm_name=None,charge_type="Daily",data_volumn=None,
              project_id=0,max_count=1,suffix=''):
    if password and (len(password)<8 or len(password)>32 or
                         re.match(r'[0-9]+', password) or
                         re.match(r'[a-z]+', password)):
        return False, '密码输入错误:密码规则为最短8字符,最长32字符,必须包含大小写英文字符和数字,支持其他可见字符'

    if not data_volumn:
        data_disk_gb=0
    else:
        data_disk_gb=int(data_volumn.strip())

    #print image_id,subnet_id,password,security_group_id,charge_type,instance_type,vm_name,data_disk_gb
    res = client.run_instances(
        MaxCount=max_count, MinCount=1, ImageId=image_id,
        SubnetId=subnet_id, InstancePassword=str(password),
        SecurityGroupId=security_group_id, ChargeType=charge_type,
        InstanceType=instance_type, PurchaseTime=0, InstanceName=vm_name,
        DataDiskGb=data_disk_gb,ProjectId=project_id,InstanceNameSuffix=suffix)
    vm_id=None
    if res.get('InstancesSet',None) not in ([],None):
        vm_id=[i['InstanceId'] for i in res['InstancesSet']]
    if vm_id:
        return True,vm_id
    else:
        return False,res


def get_vm(client, instances=None,ids=[]):
    if instances:
        instances = dict(("InstanceId.{}".format(index), instance) for index, instance in
                         enumerate(instances, 1))
        res = client.describe_instances(**instances)
    elif ids:
        i=0
        for id in ids:
            instances = {"InstanceId.{}".format(i):id}
            i+=1
        res = client.describe_instances(**instances)
    else:
        res = client.describe_instances()
    return res


if __name__ == '__main__':
    project_id=0
    count=2
    batch=True
    if batch==True:
        suffix='1'
    else:
        suffix=''
    if count<1:
        print '要输入的机器数目错误,必须输入1以上的整数'
        sys.exit(1)
    client = make_conn('kec', region)
    code,vm_id=create_vm(client,password=password,image_id=image_id,subnet_id=subnet_id,
                     security_group_id=security_group_id,vm_name=vm_name,instance_type=instance_type,
                         project_id=project_id,max_count=count,suffix=suffix)
    if not code:
        print vm_id
        sys.exit(1)
    res=get_vm(client,instances=vm_id)
    print res
    instances=res['InstancesSet']
    success=[]
    fail=[]
    while instances!=[]:
        wait=[]
        for instance in instances:
            if instance.get('InstanceState',None) and instance['InstanceState'].get('Name')=='active':
                success.append(instance['InstanceId'])
            elif instance.get('InstanceState',None) and instance['InstanceState'].get('Name')=='error':
                fail.append(instance['InstanceId'])
            else:
                wait.append(instance['InstanceId'])
        if wait==[]:
            break
        else:
            instances = get_vm(client, instances=wait)['InstancesSet']

    if fail and success:
        print '创建完成!创建成功的机器:{}\n创建失败的机器:{}'.format(','.join(success),','.join(fail))
        sys.exit(1)
    elif fail and not success:
        print '创建失败!创建失败的机器:{}'.format(','.join(fail))
        sys.exit(1)
    elif not fail and success:
        print '创建成功!创建成功的机器:{}'.format(','.join(success))

  

删除虚拟机
#coding=utf8
from kscore.session import get_session
import re


def make_conn(service_name, region):
    try:
        s = get_session()
        url = 'http://kec.{}.XXx.XXX'.format(region)
        if url.startswith('http://'):
            is_ssl = False
        else:
            is_ssl = True
        client = s.create_client(service_name, region_name=region, endpoint_url=url,
                                 use_ssl=is_ssl, ks_access_key_id=ACCESS_KEY_ID,
                                 ks_secret_access_key=SECRET_ACCESS_KEY, api_version='2016-03-04',
                                 verify=False)
        return client
    except Exception as e:
        print e


def get_vm(client, instances=None):
    if instances:
        instances = dict(("InstanceId.{}".format(index), instance) for index, instance in
                         enumerate(instances, 1))
        res = client.describe_instances(**instances)
    else:
        res = client.describe_instances()
    return res


def del_vms(client,instances=None):
    res=get_vm(client, instances=instances)
    temp=[]
    fail = []
    print res
    if res['InstanceCount']!=len(instances):
        for i in res['InstancesSet']:
            temp.append(i['InstanceId'])

        for i in temp:
            if i not in instances:
                fail.append(i)
        instances=temp
    # print fail
    # print instances
    if instances:
        instances = dict(
            ("InstanceId.{}".format(index), instance) for index, instance in enumerate(instances, 1))

        res=client.terminate_instances(**instances)
        if res.get('InstancesSet',None) :
            for i in res['InstancesSet']:
                if i.get('Return',None)!=True:
                    fail.append(i['InstanceId'])
    if fail:
        return '删除失败,失败的id为:{}'.format(','.join(fail))
    else:
        return '删除成功'


def get_vm_by_name(client,names=[],project=0):
    result=[]
    for i in names:
        instances={"InstanceName":i}#$,"MaxResults":1000}
        res = client.describe_instances(**instances)
        if res.get('InstancesSet',None):
            for i in res['InstancesSet']:
                if i['ProjectId']==project:
                    result.append(i['InstanceId'])
    return result



if __name__ == '__main__':
    client = make_conn('kec', region)
    # print client
    names=['test-1','test-2']
    project_id=0
    instances=''
    if vm_name:
        for name in vm_name.split(','):
            names.append(name)
        instances=get_vm_by_name(client,names=names,project=project_id)
    #print instances
    elif instances:
        instances=instances.split(',')
    res = del_vms(client, instances=instances)
    print res

  

上一篇:xBIM 03 基本模型操作


下一篇:java-给定一个单例:是否需要静态方法和变量?