前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于Python脚本批量设置轻量应用服务器防火墙

基于Python脚本批量设置轻量应用服务器防火墙

原创
作者头像
拖拉飞机
发布2024-02-02 22:50:10
1170
发布2024-02-02 22:50:10
举报
文章被收录于专栏:嘉钰踩坑实录嘉钰踩坑实录

批量放通同地域实例防火墙脚本。

代码语言:shell
复制
import csv
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.lighthouse.v20200324 import lighthouse_client, models

def create_firewall_rules(instance_id):
    try:
        # ID 和 Key 从该链接获取: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential("SecretID", "SecretKey")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "lighthouse.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        """
            替换下边这句里的 ap-shanghai
            如:
            1. 新加坡: ap-singapore
            2. 东京: ap-tokyo
            3. 硅谷: na-siliconvalley
            4. 法兰克福: eu-frankfurt
            5. 首尔: ap-seoul
            6. 雅加达: ap-jakarta
        """
        client = lighthouse_client.LighthouseClient(cred, "ap-shanghai", clientProfile)

        req = models.CreateFirewallRulesRequest()
        params = {

            "InstanceId": instance_id,
            "FirewallRules": [
                {
                    "Protocol": "TCP",
                    "Port": "8888",
                    "CidrBlock": "0.0.0.0/0",
                    "Action": "ACCEPT",
                    "FirewallRuleDescription": "/"
                }
            ]
        }
        req.from_json_string(json.dumps(params))

        resp = client.CreateFirewallRules(req)
        print(f"Firewall rules created for instance {instance_id}: {resp.to_json_string()}")

    except TencentCloudSDKException as err:
        print(f"Error creating firewall rules for instance {instance_id}: {err}")

def read_instance_ids_from_csv(file_path):
    instance_ids = []
    with open(file_path, newline='', encoding='utf-8-sig') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            instance_ids.append(row[0])
    return instance_ids

if __name__ == "__main__":
    csv_file_path = "data/instance_ids.csv"  # Replace with the path to your CSV file
    instance_ids = read_instance_ids_from_csv(csv_file_path)
    for instance_id in instance_ids:
        create_firewall_rules(instance_id)

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档