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

行云流水
2022-05-09 / 0 评论 / 815 阅读 / 正在检测是否收录...

前言

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

脚本内容

update_while_ip.py

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

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

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

配置

别名

vim .bashrc
alias uip='python3 /opt/project/sys/tencent/update_while_ip.py'

手动更新

uip -u f

评论 (0)

取消
只有登录/注册用户才可评论