代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。建议不要在代码中使用持久 SecretId 和 SecretKey,为了提高密钥的安全性,推荐以下几种方案:
方案1:通过环境变量读取 SecretId 和 SecretKey
将 SecretId 和 SecretKey 预先配置到环境变量中,在代码运行时从环境变量中读取 SecretId 和 SecretKey 的值,代码示例如下:
import osfrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.cvm.v20170312 import cvm_client, modelstry:# 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,不推荐# 为保护密钥安全,建议将密钥设置在环境变量中# cred = credential.Credential("secretId", "secretKey")cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),os.environ.get("TENCENTCLOUD_SECRET_KEY"))client = cvm_client.CvmClient(cred, "ap-shanghai")req = models.DescribeInstancesRequest()resp = client.DescribeInstances(req)print(resp.to_json_string())except TencentCloudSDKException as err:print(err)
环境变量配置可参考以下方式:
临时配置(当前终端会话中生效,关闭终端后失效)
export TENCENTCLOUD_SECRET_ID=您的SecretIdexport TENCENTCLOUD_SECRET_KEY=您的SecretKey
set TENCENTCLOUD_SECRET_ID=您的SecretIdset TENCENTCLOUD_SECRET_KEY=您的SecretKey
永久配置(所有终端生效,重启终端或系统后仍有效)
# 编辑环境变量文件echo 'export TENCENTCLOUD_SECRET_ID=您的SecretId' >> ~/.bashrcecho 'export TENCENTCLOUD_SECRET_KEY=您的SecretKey' >> ~/.bashrc# 使配置立即生效source ~/.bashrc
1. 右键点击此电脑,选择属性。
2. 单击高级系统设置,选择环境变量。
3. 在系统变量区域中,单击 新建,依次添加以下两个变量:
变量名:
TENCENTCLOUD_SECRET_ID
变量值:您的 SecretId。
变量名:
TENCENTCLOUD_SECRET_KEY
变量值:您的 SecretKey。
4. 添加完成后,单击确定保存配置。
验证配置是否成功
echo $TENCENTCLOUD_SECRET_IDecho $TENCENTCLOUD_SECRET_KEY
echo %TENCENTCLOUD_SECRET_ID%echo %TENCENTCLOUD_SECRET_KEY%
方案2:使用临时密钥
# 换取临时秘钥的 SDK 示例import jsonimport osfrom tencentcloud.common import credentialfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfilefrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.sts.v20180813 import sts_client, modelstry:# 实例化一个认证对象,入参需要传入腾讯云账户的secretId和secretKey,为了保护密钥安全,建议结合方案一,将密钥设置在环境变量中cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),os.environ.get("TENCENTCLOUD_SECRET_KEY"))httpProfile = HttpProfile()httpProfile.endpoint = "sts.tencentcloudapi.com"clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = sts_client.StsClient(cred, "", clientProfile)req = models.GetFederationTokenRequest()params = {}req.from_json_string(json.dumps(params))resp = client.GetFederationToken(req)print(resp.to_json_string())except TencentCloudSDKException as err:print(err)