利用Python调用云Api实现批量共享云服务器自定义镜像

2022-05-27 15:35:59 浏览数 (1)

#本文已被官方文档收录https://cloud.tencent.com/document/product/213/73390

0.准备工作

使用本代码请先进行子用户创建并授权云服务器与云API全部权限

请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

前往创建子用户:https://console.cloud.tencent.com/cam

1.SDK下载

请确保Python版本为3.6

查看Python版本

代码语言:javascript复制
python3 -V

安装腾讯云Python SDK

代码语言:javascript复制
pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python

2.代码部分

其中 aria部分请按实际情况填写 详见产品支持的地域列表

本代码调用的云API接口为:DescribeImages、ModifyImageSharePermission

代码语言:javascript复制
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

# 此处添加SecretId 与 SecretKey
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "cvm.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile

# 举例为南京 请按实际情况进行修改 例如上海请修改为ap-shanghai
aria = 'ap-nanjing'
client = cvm_client.CvmClient(cred,aria, clientProfile)
def img_share(img_id,img_name,accountids):
    try:
        req1 = models.ModifyImageSharePermissionRequest()
        params1 = {
            "ImageId": img_id,
            "AccountIds": accountids,
            "Permission": "SHARE"
        }
        req1.from_json_string(json.dumps(params1))

        resp1 = client.ModifyImageSharePermission(req1)
        response1 = json.loads(resp1.to_json_string())
        print(img_name,'共享成功!',response1)
    except TencentCloudSDKException as err:
        print(img_name,'共享失败!',err)
try:
    req = models.DescribeImagesRequest()
    params = {
        "Filters": [
            {
                "Name": "image-type",
                "Values": ["PRIVATE_IMAGE"]
            }
        ],
        "Limit": 100
    }
    req.from_json_string(json.dumps(params))
    resp = client.DescribeImages(req)
    response = json.loads(resp.to_json_string())
    img_num = response["TotalCount"]
    print('正在获取镜像列表....')
    share_config = input('1.共享所有镜像nn2.让我决定每一个镜像nn输入1或2并按回车 默认为2:') or '2'
    accountids = input('请输入被共享人uin 多个以英文逗号隔开:').split(",")
    for i in range(img_num):
        basic = response['ImageSet'][i]
        img_id = basic['ImageId']
        img_name = basic['ImageName']
        if share_config == '1':
            img_share(img_id,img_name,accountids)
        elif share_config == '2':
            print('镜像id:',img_id,'镜像名称:',img_name)
            share_choice = input('是否共享此镜像 y/n:') or 'y'
            if share_choice == 'y':
                img_share(img_id,img_name,accountids)
            elif share_choice == 'n':
                continue
            else:
                print('请输入正确的选项!!')
        else:
            print('请输入正确的选项!!')

except TencentCloudSDKException as err:
    print(err)

0 人点赞