前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用Python调用云Api实现将cvm安全组配置复制到轻量应用服务器

利用Python调用云Api实现将cvm安全组配置复制到轻量应用服务器

原创
作者头像
小宇-xiaoyu
修改2022-03-07 10:47:15
1.2K0
修改2022-03-07 10:47:15
举报
文章被收录于专栏:玩转Lighthouse.

虽然轻量应用服务器并没有安全组,但是我们可以用云api将cvm的安全组配置复制下来,生成代码调用轻量应用服务器相关api将cvm安全组配置添加到轻量防火墙

云服务器安全组地址:https://console.cloud.tencent.com/vpc/securitygroup

0.准备工作

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

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

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

1.SDK下载

请确保Python版本为3.6+

查看Python版本

代码语言:javascript
复制
python3 -V

安装腾讯云Python SDK

代码语言:javascript
复制
pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python

2.代码部分

运行结束后会生成一个新的.py文件 也可以将它理解为轻量应用服务器的安全组 运行这个文件即可将安全组配置绑定到指定的轻量应用服务器防火墙

# 安全组id为sg开头 本代码默认的地域为广州 其他地域请自行修改 代码行号为19 例如南京则修改为ap-nanjing

代码语言:javascript
复制
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.vpc.v20170312 import vpc_client, models
SecretId = input('SecretId:')
SecretKey = input('SecretKey:')
groupid = input('cvm安全组id:')
try:
    # cred = credential.Credential("SecretId", "SecretKey")
    cred = credential.Credential("{0}".format(SecretId), "{0}".format(SecretKey))
    httpProfile = HttpProfile()
    httpProfile.endpoint = "vpc.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 默认为广州地域 其他地域请自行修改 例如南京则修改为ap-nanjing
    client = vpc_client.VpcClient(cred, "ap-guangzhou", clientProfile)

    req = models.DescribeSecurityGroupPoliciesRequest()
    params = {
        "SecurityGroupId": groupid
    }
    req.from_json_string(json.dumps(params))

    resp = client.DescribeSecurityGroupPolicies(req)
    response = json.loads(resp.to_json_string())
    # print(response)
    rules_num = len(response['SecurityGroupPolicySet']['Ingress'])
    # print(rules_num)
    protocol_list = []
    port_list = []
    cidrblock_list = []
    action_list = []
    description_list = []
    rules_list = []
    for i in range(rules_num):
        ii = response['SecurityGroupPolicySet']['Ingress'][i]
        # {'Protocol': 'udp', 'Port': 'ALL', 'CidrBlock': '10.0.0.0/8',  'Action': 'ACCEPT', 'PolicyDescription': ''}
        protocol = ii['Protocol']

        port = ii['Port']

        cidrblock = ii['CidrBlock']

        action = ii['Action']

        description = ii['PolicyDescription']


        rule = '''{{"Protocol": '{0}',"Port": '{1}',"CidrBlock":'{2}',"Action":'{3}',"FirewallRuleDescription":'{4}'}}'''.format(protocol.upper(), port,cidrblock,action,description)
        rules_list.append(rule)
    rules = ",".join(str(i) for i in rules_list)
    # print(rules)
    code = '''import json
from time import strftime, localtime, 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

start = time()
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("{0}", "{1}")
httpProfile = HttpProfile()
httpProfile.endpoint = "lighthouse.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile

for i in range(12):
    client = lighthouse_client.LighthouseClient(cred, aria[i], clientProfile)
    # 获取实例信息
    try:
        # 查看所有实例
        req = models.DescribeInstancesRequest()
        params = {{}}
        req.from_json_string(json.dumps(params))

        resp = client.DescribeInstances(req)

        response = json.loads(resp.to_json_string())

        # print(response)
        # 实例详细信息
        basic = response['InstanceSet']
        # 判断地域是否含有实例
        if response['TotalCount'] > 0:
            print(aria[i] + '实例数为' + str(response['TotalCount']))
            # 提取返回的json信息
            for ii in range(response['TotalCount']):
                ii1 = basic[ii]
                id = ii1['InstanceId']
                name = ii1['InstanceName']
                ip = ii1['PublicAddresses'][0]
                zone = ii1['Zone']
                ct = ii1['CreatedTime']
                et = ii1['ExpiredTime']
                os = ii1['OsName']
                state = ii1['InstanceState']
                login = ii1['LoginSettings']['KeyIds']
                if len(login) == 0:
                    login_staus = '否'
                else:
                    login_staus = '是'
                # 查看流量包
                try:
                    req1 = models.DescribeInstancesTrafficPackagesRequest()

                    params1 = {{
                        "InstanceIds": [id]
                    }}
                    req1.from_json_string(json.dumps(params1))
                    resp1 = client.DescribeInstancesTrafficPackages(req1)

                    response1 = json.loads(resp1.to_json_string())
                    tf = response1['InstanceTrafficPackageSet'][0]['TrafficPackageSet'][0]
                    # 总流量
                    tft = str(round(tf['TrafficPackageTotal'] / 1073741824, 2))
                    # 已用流量
                    tfu = str(round(tf['TrafficUsed'] / 1073741824, 2))
                    # 剩余流量
                    tfr = str(round(tf['TrafficPackageRemaining'] / 1073741824, 2))
                    # 已用流量%
                    percent_tfu = round(
                        round(tf['TrafficUsed'] / 1073741824, 2) / round(tf['TrafficPackageTotal'] / 1073741824,
                                                                         2) * 100, 3)
                    # 剩余流量%
                    percent_tfr = 100 - percent_tfu
                    # 判断实例已用流量是否达到预设值(1即为1%)
                    if percent_tfu > 1.000:
                        print('IP为:' + ip + '实例Id为: ' + id + '的流量已达到预设值',
                              '时间:' + strftime('%Y-%m-%d %H:%M:%S', localtime()), sep='\\n')

                except TencentCloudSDKException as err:
                    print(err)

                print('--------------------------------',
                      'id: ' + id,
                      '实例名称:' + name,
                      '实例状态: ' + state,
                      'ip: ' + ip,
                      '实例大区:' + zone,
                      '创建时间: ' + ct,
                      '到期时间: ' + et,
                      '操作系统: ' + os,
                      '总流量:' + tft + 'GB',
                      '已用流量(%): ' + tfu + 'GB' + ' (' + str(percent_tfu) + '%)',
                      '剩余流量: ' + tfr + 'GB' + ' (' + str(percent_tfr) + '%)',
                      '该实例是否绑定密钥:'+ login_staus,
                      '请求发送时间:' + strftime('%Y-%m-%d %H:%M:%S', localtime()),
                      '--------------------------------',sep='\\n')
                # 防火墙
                bind = input('是否绑定安全组?y/n(n)')
                if bind == 'y':
                    try:
                        
                        req2 = models.CreateFirewallRulesRequest()
                        params2 = {{
                            "InstanceId": id,
                            "FirewallRules": [{2}]
                        }}
                        req2.from_json_string(json.dumps(params2))
                    
                        resp2 = client.CreateFirewallRules(req2)
                        print(resp2.to_json_string())
                    except TencentCloudSDKException as err:
                        print(err)
                else:
                    continue
    except TencentCloudSDKException as err:
        print(err)

end = time()
print('本次代码执行共耗时:', round(end - start, 2), 's')'''.format(SecretId, SecretKey, rules)
    # print(code)
    key = open("{0}.py".format(groupid), mode='w',encoding='utf-8')
    key.write(code)
    key.close()
    print('代码生成成功!名称为{0}.py'.format(groupid))
except TencentCloudSDKException as err:
    print(err)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 0.准备工作
  • 1.SDK下载
  • 2.代码部分
相关产品与服务
轻量应用服务器
轻量应用服务器(TencentCloud Lighthouse)是新一代开箱即用、面向轻量应用场景的云服务器产品,助力中小企业和开发者便捷高效的在云端构建网站、Web应用、小程序/小游戏、游戏服、电商应用、云盘/图床和开发测试环境,相比普通云服务器更加简单易用且更贴近应用,以套餐形式整体售卖云资源并提供高带宽流量包,将热门软件打包实现一键构建应用,提供极简上云体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档