新闻、帮助、产品更新动态

最新的业界新闻,产品系统更新开发动态,帮助教程和活动发布

利用Python调用云API实现多地域同步创建TAT命令

发布日:2021-12-24 14:40       阅读数:

0.准备工作

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

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

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

1.SDK下载

请确保Python版本为3.6+

查看Python版本

python3 -V

安装腾讯云Python SDK

pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python

2.代码部分

import base64,random,string
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.tat.v20201028 import tat_client, models
# 默认为轻量应用服务器所支持的12个地域
aria = ['ap-beijing', 'ap-chengdu', 'ap-guangzhou', 'ap-hongkong', 'ap-shanghai', 'ap-singapore',
        'na-siliconvalley',
        'eu-moscow', 'ap-tokyo', 'ap-nanjing', 'ap-mumbai', 'eu-frankfurt']
# 此处填写你的"SecretId", "SecretKey"
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "tat.tencentcloudapi.com"
# command
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
input('按回车开始输入命令,输入完毕输入:wq 按回车结束')
stopword = ':wq' # 输入停止符
string = ''
for line in iter(input, stopword):
  string += line + '\n'
# 将命令转为base64编码
encodestr = base64.b64encode(string.encode('utf-8'))
Content = str(encodestr, 'utf-8')
print(Content)
# 命令名称若不填写即随机填写8位字符串
CommandName = input('命令名称:')or ran_str
Description = input('命令描述:')
# 命令类型 默认为SHELL
CommandType = input('命令类型(SHELL、POWERSHELL):') or "SHELL"
Timeout = input('超时时间(默认60 取值范围[1, 86400])') or 60

clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
for i in range(12):
    client = tat_client.TatClient(cred, aria[i], clientProfile)
    try:
        req = models.CreateCommandRequest()
        params = {
            "CommandName": "{0}".format(CommandName),
            "Description": "{0}".format(Description),
            "Content": "{0}".format(Content),
            "CommandType": "{0}".format(CommandType),
            "Timeout": Timeout
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreateCommand(req)
        print(resp.to_json_string())

    except TencentCloudSDKException as err:
       import base64,random,string
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.tat.v20201028 import tat_client, models
# 默认为轻量应用服务器所支持的12个地域
aria = ['ap-beijing', 'ap-chengdu', 'ap-guangzhou', 'ap-hongkong', 'ap-shanghai', 'ap-singapore',
        'na-siliconvalley',
        'eu-moscow', 'ap-tokyo', 'ap-nanjing', 'ap-mumbai', 'eu-frankfurt']
# 此处填写你的"SecretId", "SecretKey"
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "tat.tencentcloudapi.com"
# command
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
input('按回车开始输入命令,输入完毕输入:wq 按回车结束')
stopword = ':wq' # 输入停止符
string = ''
for line in iter(input, stopword):
  string += line + '\n'
# 将命令转为base64编码
encodestr = base64.b64encode(string.encode('utf-8'))
Content = str(encodestr, 'utf-8')
print(Content)
# 命令名称若不填写即随机填写8位字符串
CommandName = input('命令名称:')or ran_str
Description = input('命令描述:')
# 命令类型 默认为SHELL
CommandType = input('命令类型(SHELL、POWERSHELL):') or "SHELL"
Timeout = input('超时时间(默认60 取值范围[1, 86400])') or 60

clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
for i in range(12):
    client = tat_client.TatClient(cred, aria[i], clientProfile)
    try:
        req = models.CreateCommandRequest()
        params = {
            "CommandName": "{0}".format(CommandName),
            "Description": "{0}".format(Description),
            "Content": "{0}".format(Content),
            "CommandType": "{0}".format(CommandType),
            "Timeout": Timeout
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreateCommand(req)
        print(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)

3.若报错请对照下方错误码列表排查

公共错误码

错误码

说明

ActionOffline

接口已下线。

AuthFailure.InvalidAuthorization

请求头部的 Authorization 不符合腾讯云标准。

AuthFailure.InvalidSecretId

密钥非法(不是云 API 密钥类型)。

AuthFailure.MFAFailure

MFA 错误。

AuthFailure.SecretIdNotFound

密钥不存在。请在控制台检查密钥是否已被删除或者禁用,如状态正常,请检查密钥是否填写正确,注意前后不得有空格。

AuthFailure.SignatureExpire

签名过期。Timestamp 和服务器时间相差不得超过五分钟,请检查本地时间是否和标准时间同步。

AuthFailure.SignatureFailure

签名错误。签名计算错误,请对照调用方式中的签名方法文档检查签名计算过程。

AuthFailure.TokenFailure

token 错误。

AuthFailure.UnauthorizedOperation

请求未授权。请参考 CAM 文档对鉴权的说明。

DryRunOperation

DryRun 操作,代表请求将会是成功的,只是多传了 DryRun 参数。

FailedOperation

操作失败。

InternalError

内部错误。

InvalidAction

接口不存在。

InvalidParameter

参数错误(包括参数格式、类型等错误)。

InvalidParameterValue

参数取值错误。

InvalidRequest

请求 body 的 multipart 格式错误。

IpInBlacklist

IP地址在黑名单中。

IpNotInWhitelist

IP地址不在白名单中。

LimitExceeded

超过配额限制。

MissingParameter

缺少参数。

NoSuchProduct

产品不存在

NoSuchVersion

接口版本不存在。

RequestLimitExceeded

请求的次数超过了频率限制。

RequestLimitExceeded.GlobalRegionUinLimitExceeded

主账号超过频率限制。

RequestLimitExceeded.IPLimitExceeded

IP限频。

RequestLimitExceeded.UinLimitExceeded

主账号限频。

RequestSizeLimitExceeded

请求包超过限制大小。

ResourceInUse

资源被占用。

ResourceInsufficient

资源不足。

ResourceNotFound

资源不存在。

ResourceUnavailable

资源不可用。

ResponseSizeLimitExceeded

返回包超过限制大小。

ServiceUnavailable

当前服务暂时不可用。

UnauthorizedOperation

未授权操作。

UnknownParameter

未知参数错误,用户多传未定义的参数会导致错误。

UnsupportedOperation

操作不支持。

UnsupportedProtocol

http(s) 请求协议错误,只支持 GET 和 POST 请求。

UnsupportedRegion

接口不支持所传地域。

业务错误码

错误码

说明

AuthFailure

CAM签名/鉴权错误。

FailedOperation.CVMError

调用 CVM 失败。

FailedOperation.LighthouseError

调用 Lighthouse 失败。

InvalidParameter.ConflictParameter

参数冲突。

InvalidParameterValue.AgentUnsupportedCommandType

Agent不支持此命令类型。

InvalidParameterValue.CommandContentInvalid

Command 内容无效。

InvalidParameterValue.CommandNameDuplicated

Command 名称重复。

InvalidParameterValue.InconsistentInstance

实例类型不一致。

InvalidParameterValue.InstanceIsNotRelatedToInvocation

实例ID与执行活动无关。

InvalidParameterValue.InvalidCommandId

CommandId 无效。

InvalidParameterValue.InvalidCommandName

Command 名称无效。

InvalidParameterValue.InvalidContent

命令内容无效。

InvalidParameterValue.InvalidCronExpression

Crontab 表达式无效。

InvalidParameterValue.InvalidFilter

Filter 无效。

InvalidParameterValue.InvalidInstanceId

实例ID无效。

InvalidParameterValue.InvalidInvocationId

不合法的执行活动ID。

InvalidParameterValue.InvalidInvocationTaskId

不合法的执行任务ID。

InvalidParameterValue.InvalidInvokerId

InvokerId 无效。

InvalidParameterValue.InvalidOutputCOSBucketUrl

OutputCOSBucketUrl 无效。

InvalidParameterValue.InvalidOutputCOSKeyPrefix

OutputCOSKeyPrefix 无效。

InvalidParameterValue.InvalidWorkingDirectory

命令执行路径不合法。

InvalidParameterValue.LackOfParameterInfo

已启用自定义参数功能,但缺失自定义参数信息。

InvalidParameterValue.LackOfParameters

未提供 Parameters 信息。

InvalidParameterValue.LimitExceeded

超过参数限制。

InvalidParameterValue.ParameterDisabled

未启用自定义参数功能。

InvalidParameterValue.ParameterInvalidJsonFormat

参数为非法 json string 格式。

InvalidParameterValue.ParameterKeyContainsInvalidChar

参数 Key 包含非法字符。

InvalidParameterValue.ParameterKeyDuplicated

参数 Key 重复。

InvalidParameterValue.ParameterKeyLenExceeded

参数 Key 过长。

InvalidParameterValue.ParameterNumberExceeded

参数数目过多。

InvalidParameterValue.ParameterValueNotString

参数 Value 非 string 类型。

InvalidParameterValue.Range

参数取值范围不合法。

InvalidParameterValue.SupportParametersOnlyIfEnableParameter

未启用自定义参数功能。

InvalidParameterValue.TooLong

长度超过限制。

ResourceNotFound.CommandNotFound

命令不存在。

ResourceNotFound.InstanceNotFound

实例不存在。

ResourceNotFound.InvocationNotFound

执行活动未找到。

ResourceUnavailable.AgentNotInstalled

Agent 未安装。

ResourceUnavailable.AgentStatusNotOnline

Agent 不在线。

ResourceUnavailable.CommandInExecuting

命令正在执行中。

ResourceUnavailable.CommandInInvoker

命令已关联执行器。

ResourceUnavailable.InstanceStateNotRunning

实例未处于运行中。

UnauthorizedOperation.CamAuthFailed

CAM鉴权失败。

UnauthorizedOperation.InvalidToken

Token 无效。

UnauthorizedOperation.MFAExpired

Multi-Factor Authentication(MFA) 过期。

UnauthorizedOperation.MFANotFound

Multi-Factor Authentication(MFA) 不存在。


编辑:航网科技   来源:腾讯云

本文版权归原作者所有 转载请注明出处

联系我们

客服部:深圳市龙华区龙胜商业大厦5楼B5区

业务部:深圳市南山区讯美科技广场2栋12楼1202

资质证书

  • Copyright © 2011-2020 www.hangw.com. All Rights Reserved 深圳航网科技有限公司 版权所有 增值电信业务经营许可证:粤B2-20201122 - 粤ICP备14085080号

    在线客服

    微信扫一扫咨询客服


    全国免费服务热线
    0755-36300002

    返回顶部