基于Python脚本批量重装轻量应用服务器系统

2024-02-02 22:48:50 浏览数 (1)

背景:腾讯云轻量应用服务器一直没支持批量重装系统,于是用Python写了个脚本,处理同地域多台实例重装系统的需求。

代码语言:python代码运行次数:0复制
import json
import csv
import time
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.lighthouse.v20200324 import lighthouse_client, models

# 设置您的腾讯云SecretID和SecretKey, 获取地址: https://console.cloud.tencent.com/cam/capi
secret_id = "your_secret_id"
secret_key = "your_secret_key"

csv_file = "instance_id.csv"
# 设置CSV文件路径,可以在轻量应用服务器选择导出实例信息,默认为csv文件

try:
    cred = credential.Credential(secret_id, secret_key)
    httpProfile = HttpProfile()
    httpProfile.endpoint = "lighthouse.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = lighthouse_client.LighthouseClient(cred, "ap-guangzhou", clientProfile)
    # 注意地域

    req = models.ResetInstanceRequest()
    params = {
        "InstanceId": "",
        "BlueprintId": "lhbp-i0sjva9u",  
        # 设置要重装的镜像ID,注意镜像的地域要和实例的保持一致,例如:lhbp-hwey1fjw
        # 镜像ID可以通过请求DescribeBlueprints接口来实现
        # 参考:https://cloud.tencent.com/document/product/1207/47689
    }

    with open(csv_file, 'r') as file:
        csv_reader = csv.reader(file)
        next(csv_reader)  # 跳过标题行
        for row in csv_reader:
            instance_id = row[0]
            params["InstanceId"] = instance_id
            req.from_json_string(json.dumps(params))

            resp = client.ResetInstance(req)
            print("Instance %s reset success" % instance_id)
            time.sleep(1)  # 休眠1秒,防止频繁调用达到API限制

except TencentCloudSDKException as err:
    print("%s error: %s" % (instance_id, err))

0 人点赞