前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用python脚本自动更新腾讯云安全组防火墙白名单

利用python脚本自动更新腾讯云安全组防火墙白名单

作者头像
IT不难
发布2022-05-11 14:29:38
1K0
发布2022-05-11 14:29:38
举报
文章被收录于专栏:IT不难技术家园
l2ywol3n.png
l2ywol3n.png

前言

经常在家里,公司等地方远程管理腾讯云的vps,本来想讲固定IP添加到防火墙白名单。可是家里的IP经常变化,于是写了个脚本。调用腾讯云的api更新防火墙白名单IP地址。

脚本内容

update_while_ip.py

代码语言:javascript
复制
import requests
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
import argparse
from setting  import *
import datetime, os

def AddGroupRole(config, sourceip):
    try:
        cred = credential.Credential(config['SecretId'], config['SecretKey'])
        httpProfile = HttpProfile()
        httpProfile.endpoint = "vpc.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = vpc_client.VpcClient(cred, config['Region'], clientProfile)

        #req = models.CreateSecurityGroupPoliciesRequest()
        req = models.ModifySecurityGroupPoliciesRequest()

        params = {
            "SecurityGroupPolicySet": {
                "Ingress": [
                    {
                        "Protocol": "ALL",
                        "CidrBlock": sourceip,
                        "Action": "ACCEPT",
                        "PolicyDescription": "mac当前公网IP"
                    },
                    {
                        "Protocol": "ALL",
                        "CidrBlock": '1.2.3.44',
                        "Action": "ACCEPT",
                        "PolicyDescription": "堡垒机"
                    },
                ]
            },
            "SecurityGroupId": config['SecurityGroupId']
        }
        req.from_json_string(json.dumps(params))

        #resp = client.CreateSecurityGroupPolicies(req)
        resp = client.ModifySecurityGroupPolicies(req)
        print('{}:{}'.format(config['description'], resp.to_json_string()))

    except TencentCloudSDKException as err:
        print(err)

def GetCompanyOldIp():
    '''
    读旧IP
    '''
    if not  os.path.exists(IPFILE):
        return '0.0.0.0'
    with open(IPFILE, 'r') as fr:
        oldip = fr.read().strip()
    return oldip

def WriteIp(sip):
    '''
    写新IP
    '''
    with open(IPFILE, 'w') as fw:
        fw.write(sip)

def UpdateWhiteIP(tag):
    '''
    更新IP白名单函数
    '''
    OldIp = GetCompanyOldIp()
    NewIp = requests.get(url="https://ifconfig.me/ip").text
    if tag == 'f':
        for item in TCONFIG:
            AddGroupRole(item, NewIp)

    if NewIp != OldIp:
        print('{}======公网ip更新:{}--->{}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), OldIp, NewIp))
        if tag == 'all':
            for item in TCONFIG:
                AddGroupRole(item, NewIp)

        if tag == 'm':
            AddGroupRole(TCONFIG[0], NewIp)

        if tag == 'a':
            AddGroupRole(TCONFIG[1], NewIp)
    #保存IP
    WriteIp(NewIp)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="更新信任IP白名单")
    parser.add_argument("-u","--update", help="m:我的腾讯云,a:公司, all:全部", type=str, choices=['m', 'a', 'f', 'all'],  default='all')
    args = parser.parse_args()

    if args.update in ['m', 'a', 'f', 'all']:
        UpdateWhiteIP(args.update)
    else:
        print('参数非法')
    exit()

配置文件 setting.py

代码语言:javascript
复制
#配置信息列表
TCONFIG = [
    {
    "description":"我的腾讯云主机",
    "SecretId": "AKIDGPL2VxxxxxxxxxxxxxxxY6XyITuCJ",   #腾讯云API接口密钥
    "SecretKey": "EKG6oOsDxxxxxxxxxxxxxxGJ8mHfy",  #secretkey
    "Region": "ap-shanghai",           #vps 安全组所在地区
    "SecurityGroupId": "sg-3baexxx"   #安全组IP
    },
]

#保存IP文件
IPFILE='/tmp/ip.txt'

配置

别名

代码语言:javascript
复制
vim .bashrc
alias uip='python3 /opt/project/sys/tencent/update_while_ip.py'

手动更新

代码语言:javascript
复制
uip -u f

本文共 164 个字数,平均阅读时长 ≈ 1分钟

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 脚本内容
    • update_while_ip.py
      • 配置文件 setting.py
      • 配置
        • 别名
          • 手动更新
          相关产品与服务
          运维安全中心(堡垒机)
          腾讯云运维安全中心(堡垒机)(Operation and Maintenance Security Center (Bastion Host))可为您的 IT 资产提供代理访问以及智能操作审计服务,为客户构建一套完善的事前预防、事中监控、事后审计安全管理体系,助力企业顺利通过等保测评。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档