程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Using Python to call cloud API to realize multi region synchronous creation of Tat command

編輯:Python

Tencent cloud lightweight worry free plan New and old users enjoy the same discount As low as 15 element / Month begins Lifetime renewal at the same price A year's worth of top-level domain names , And enjoy long-term renewal discount

Activity Links :https://cloud.tencent.com/act/lighthouse

( The event will be held in 2021.12.31 end )

Automation assistant (TencentCloud Automation Tools,TAT) It is the original operation and maintenance deployment tool of ECs .TAT Provide automatic remote operation mode , You can directly manage instances , Batch execution Shell,Powershell,Python Wait for the order , It is easy to complete the operation and maintenance script 、 polling process 、 Install or uninstall software 、 Common management tasks such as updating applications and installing patches .

0. preparation

Please use this code first Child users create And authorize cloud API And TAT All permissions

Please note that To ensure the security of your account and cloud assets Please keep it carefully SecretId And SecretKey And regularly update Delete useless permissions

Go to create sub user :https://console.cloud.tencent.com/cam

1.SDK download

Please make sure Python Version is 3.6+

see Python edition

python3 -V

Install Tencent cloud Python SDK

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

2. Code section

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
# The default is supported by lightweight application servers 12 Regions
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']
# Fill in your "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(' Press enter to start entering the command , After input, input :wq Press enter to finish ')
stopword = ':wq' # Enter the stop character
string = ''
for line in iter(input, stopword):
string += line + '\n'
# Change the command to base64 code
encodestr = base64.b64encode(string.encode('utf-8'))
Content = str(encodestr, 'utf-8')
print(Content)
# If the command name is not filled in, it is filled in randomly 8 A string
CommandName = input(' Command name :')or ran_str
Description = input(' Command description :')
# Command type The default is SHELL
CommandType = input(' Command type (SHELL、POWERSHELL):') or "SHELL"
Timeout = input(' Timeout time ( Default 60 Value range [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. If an error is reported, please check the error code list below

Common error code

Error code

explain

ActionOffline

The interface is offline .

AuthFailure.InvalidAuthorization

Asking for the head  Authorization  Does not comply with Tencent cloud standards .

AuthFailure.InvalidSecretId

Illegal key ( It's not a cloud API Key type ).

AuthFailure.MFAFailure

MFA  error .

AuthFailure.SecretIdNotFound

The key does not exist . Please check whether the key has been deleted or disabled in the console , As normal , Please check whether the key is filled in correctly , Note that there should be no spaces before and after .

AuthFailure.SignatureExpire

Signature expired .Timestamp No more than five minutes from the server time , Please check whether the local time is synchronized with the standard time .

AuthFailure.SignatureFailure

Signature error . Signature calculation error , Please check the signature calculation process against the signature method document in the calling method .

AuthFailure.TokenFailure

token error .

AuthFailure.UnauthorizedOperation

Request not authorized . Please refer to  CAM  Document description of Authentication .

DryRunOperation

DryRun operation , The representative request will be successful , It's just an extra pass DryRun Parameters .

FailedOperation

operation failed .

InternalError

internal error .

InvalidAction

Interface does not exist .

InvalidParameter

Parameter error ( Including parameter format 、 Type and other errors ).

InvalidParameterValue

Parameter value error .

InvalidRequest

request body Of multipart Format error .

IpInBlacklist

IP The address is on the blacklist .

IpNotInWhitelist

IP Address not on white list .

LimitExceeded

Quota limit exceeded .

MissingParameter

Lack of parameter .

NoSuchProduct

The product doesn't exist

NoSuchVersion

Interface version does not exist .

RequestLimitExceeded

The number of requests exceeded the frequency limit .

RequestLimitExceeded.GlobalRegionUinLimitExceeded

The primary account exceeds the frequency limit .

RequestLimitExceeded.IPLimitExceeded

IP Frequency limiting .

RequestLimitExceeded.UinLimitExceeded

The frequency of the primary account is limited .

RequestSizeLimitExceeded

The requested packet exceeds the limit size .

ResourceInUse

Resources are being used .

ResourceInsufficient

Insufficient resources .

ResourceNotFound

Resource does not exist .

ResourceUnavailable

Resource not available .

ResponseSizeLimitExceeded

The returned packet exceeds the limit size .

ServiceUnavailable

The current service is temporarily unavailable .

UnauthorizedOperation

Unauthorized operation .

UnknownParameter

Unknown parameter error , If the user passes undefined parameters, an error will occur .

UnsupportedOperation

Operation does not support .

UnsupportedProtocol

http(s) Request protocol error , Only support GET and POST request .

UnsupportedRegion

The interface does not support the passed region .

Business error code

Error code

explain

AuthFailure

CAM Signature / Authentication error .

FailedOperation.CVMError

call CVM Failure .

FailedOperation.LighthouseError

call Lighthouse Failure .

InvalidParameter.ConflictParameter

Parameter conflict .

InvalidParameterValue.AgentUnsupportedCommandType

Agent This command type is not supported .

InvalidParameterValue.CommandContentInvalid

Command Invalid content .

InvalidParameterValue.CommandNameDuplicated

Command Duplicate name .

InvalidParameterValue.InconsistentInstance

Instance types are inconsistent .

InvalidParameterValue.InstanceIsNotRelatedToInvocation

example ID Not related to the execution of activities .

InvalidParameterValue.InvalidCommandId

CommandId Invalid .

InvalidParameterValue.InvalidCommandName

Command name invalid .

InvalidParameterValue.InvalidContent

Invalid command contents .

InvalidParameterValue.InvalidCronExpression

Crontab The expression is invalid .

InvalidParameterValue.InvalidFilter

Filter Invalid .

InvalidParameterValue.InvalidInstanceId

example ID Invalid .

InvalidParameterValue.InvalidInvocationId

Illegal execution activities ID.

InvalidParameterValue.InvalidInvocationTaskId

Illegal execution of tasks ID.

InvalidParameterValue.InvalidInvokerId

InvokerId Invalid .

InvalidParameterValue.InvalidOutputCOSBucketUrl

OutputCOSBucketUrl Invalid .

InvalidParameterValue.InvalidOutputCOSKeyPrefix

OutputCOSKeyPrefix Invalid .

InvalidParameterValue.InvalidWorkingDirectory

Illegal command execution path .

InvalidParameterValue.LackOfParameterInfo

Custom parameter feature enabled , But the user-defined parameter information is missing .

InvalidParameterValue.LackOfParameters

Did not provide a Parameters Information .

InvalidParameterValue.LimitExceeded

Parameter limit exceeded .

InvalidParameterValue.ParameterDisabled

The custom parameter function is not enabled .

InvalidParameterValue.ParameterInvalidJsonFormat

The parameter is illegal json string Format .

InvalidParameterValue.ParameterKeyContainsInvalidChar

Parameters Key Contains illegal characters .

InvalidParameterValue.ParameterKeyDuplicated

Parameters Key repeat .

InvalidParameterValue.ParameterKeyLenExceeded

Parameters Key Too long .

InvalidParameterValue.ParameterNumberExceeded

Too many arguments .

InvalidParameterValue.ParameterValueNotString

Parameters Value Not string type .

InvalidParameterValue.Range

Illegal parameter value range .

InvalidParameterValue.SupportParametersOnlyIfEnableParameter

The custom parameter function is not enabled .

InvalidParameterValue.TooLong

Length exceeds limit .

ResourceNotFound.CommandNotFound

The order does not exist .

ResourceNotFound.InstanceNotFound

Instance does not exist .

ResourceNotFound.InvocationNotFound

Execution activity not found .

ResourceUnavailable.AgentNotInstalled

Agent Not installed .

ResourceUnavailable.AgentStatusNotOnline

Agent Not online .

ResourceUnavailable.CommandInExecuting

The command is being executed .

ResourceUnavailable.CommandInInvoker

The command is already associated with an actuator .

ResourceUnavailable.InstanceStateNotRunning

Instance is not running .

UnauthorizedOperation.CamAuthFailed

CAM Authentication failure .

UnauthorizedOperation.InvalidToken

Token Invalid .

UnauthorizedOperation.MFAExpired

Multi-Factor Authentication(MFA) Be overdue .

UnauthorizedOperation.MFANotFound

Multi-Factor Authentication(MFA) non-existent .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved