Python | 一个密钥管理全部腾讯云服务器足以

本文介绍了如何通过腾讯云API解决CVM和Lighthouse之间密钥不互通的问题,作者分享了使用PythonSDK创建、同步和导入密钥的方法,以简化在多地域服务器间的密钥管理过程。
摘要由CSDN通过智能技术生成

不知大家有没有用过腾讯云的密钥管理

云服务器(cvm)与轻量应用服务器(lighthouse)的密钥并不互通

而且轻量应用服务器的密钥并不像云服务器的密钥那样全地域通用,这就导致我如果有多个地域的机器,就需要创建多个密钥,或者多次创建密钥,十分麻烦

作者去研究了一下腾讯云的云API,发现只要联动几个接口即可实现同一密钥管理云服务器与轻量应用服务器的所有机器

简单原理为 先调用轻量应用服务器的查询地域接口,获取全部轻量应用服务器的地域,根据用户选择的同步模式进行相关的API接口调用。如果是自动创建公钥模式,就会调用腾讯云的创建密钥接口,获取到公私钥之后,将私钥保存到本地,然后再依次调用导入密钥接口;如果是选择使用现有公钥,就直接调用导入密钥接口。

0.准备工作

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

请注意 为了保障您的账户以及云上资产的安全 请谨慎保管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 json
import tencentcloud.cvm.v20170312.cvm_client
import tencentcloud.cvm.v20170312.models
from time import time
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.lighthouse.v20200324 import lighthouse_client, models


class SyncKey:
    def __init__(self):
        # 此处添加SecretId 与 SecretKey
        self.cred = credential.Credential("SecretId", "SecretKey")

    def get_lh_region(self):
        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.DescribeRegionsRequest()
        req.from_json_string(json.dumps({}))
        resp = lighthouse_client.LighthouseClient(self.cred, "").DescribeRegions(req)
        lh_region = []
        for region in resp.RegionSet:
            lh_region.append(region.Region)
        return lh_region

    def create_key(self, key_name):
        req = models.CreateKeyPairRequest()
        params = {
            "KeyName": key_name
        }
        req.from_json_string(json.dumps(params))

        resp = lighthouse_client.LighthouseClient(self.cred, 'ap-beijing').CreateKeyPair(req)
        response = json.loads(resp.to_json_string())
        public_key = response['KeyPair']['PublicKey']
        private_key = response['KeyPair']['PrivateKey']
        key = open(key_name+'.key', mode='w')
        key.write(private_key)
        key.close()
        print('私钥已输出至文件:', key_name+'.key')
        # print(resp.to_json_string())
        return public_key

    def sync_key(self, key_name, public_key, lh_region,sync_mode):
        for region in lh_region:
            if sync_mode == 0 and region == 'ap-beijing':
                continue
            try:
                req = models.ImportKeyPairRequest()
                params = {
                    "KeyName": key_name,
                    "PublicKey": public_key
                }
                req.from_json_string(json.dumps(params))

                resp = lighthouse_client.LighthouseClient(self.cred, region).ImportKeyPair(req)
                print(resp.to_json_string())

            except TencentCloudSDKException as err:
                print(err)
        cvm_import_key = tencentcloud.cvm.v20170312.models.ImportKeyPairRequest()
        cvm_import_key_params = {
            "KeyName": key_name,
            "ProjectId": 0,
            "PublicKey": public_key
        }
        cvm_import_key.from_json_string(json.dumps(cvm_import_key_params))

        cvm_import_key_resp = tencentcloud.cvm.v20170312.cvm_client.CvmClient(self.cred, 'ap-beijing').ImportKeyPair(cvm_import_key)
        print(cvm_import_key_resp.to_json_string())


if __name__ == '__main__':
    start = time()
    Sync_key = SyncKey()
    key_name = input('key_name: ')
    sync_mode = 1 if input('sync_mode\n0:自动创建公钥,自动储存私钥。\n1:使用现有公钥\n请输入数字,默认为0:') == '1' else 0
    if sync_mode == 1:
        input('按回车后粘贴公钥,粘贴完毕换行输入:wq 按回车结束')
        stopword = ':wq'  # 输入停止符
        public_key = ''
        for line in iter(input, stopword):
            public_key += line + '\n'
        Sync_key.sync_key(key_name, public_key, Sync_key.get_lh_region(),sync_mode)

    else:
        Sync_key.sync_key(key_name,Sync_key.create_key(key_name),Sync_key.get_lh_region(),sync_mode)
    end = time()
    print('本次代码执行共耗时:', round(end - start, 2), 's')

3.效果图:

sync_mode = 0

image.png

sync_mode = 1

image.png

lighthouse:

image.png

cvm:

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值