Python_动态解析域名更换安全组规则

简介

由于腾讯云安全组不支持添加域名,导致一些服务依赖外部域名的 有时会因为域名解析的IP更新而无法访问,最近又在学习python,特写了下面这个脚本,来实现自动获取域名解析出来的IP更改安全组规则和添加路由表规则

脚本

需要安装腾讯SDK环境

pip install --upgrade tencentcloud-sdk-python

腾讯SDK GitHub地址:https://github.com/TencentCloud/tencentcloud-sdk-python

水平有限,请见谅

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 os
import re
import datetime

# -*- coding: UTF-8 -*-


domainName = "api.weixin.qq.com"
appID = ""
appKey = ""
SecurityGroupID = "sg"
Action = "ACCEPT"
Protocol = "TCP"
Port = 443
cTime = datetime.datetime.now()



def CreateSecurityGroupPolicies(appID, appKey, SecurityGroupID,Action,Protocol, Port, domainName,IP,cTime):
        try:
                cred = credential.Credential(appID,appKey)
                httpProfile = HttpProfile()
                httpProfile.endpoint = "vpc.ap-shanghai-fsi.tencentcloudapi.com"

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = vpc_client.VpcClient(cred, "ap-shanghai-fsi", clientProfile)

                req = models.CreateSecurityGroupPoliciesRequest()
                params = {
                        "SecurityGroupPolicySet": {
                                "Egress": [
                                        {
                                                "Protocol": "%s"%(Protocol),
                                                "Port": "%s"%(Port),
                                                "CidrBlock": "%s"%(IP),
                                                "Action": "%s"%(Action),
                                                "PolicyDescription": "%s %s"%(domainName,cTime)
                                        }
                                ]
                        },
                        "SecurityGroupId": "%s"%(SecurityGroupID)
                }
                #print(params)
                req.from_json_string(json.dumps(params))

                resp = client.CreateSecurityGroupPolicies(req)
                print(resp.to_json_string())

        except TencentCloudSDKException as err:
                print(err)

def DescribeSecurityGroupPolicies(appID, appKey, SecurityGroupID,ip):
        try:
                cred = credential.Credential(appID, appKey)
                httpProfile = HttpProfile()
                httpProfile.endpoint = "vpc.ap-shanghai-fsi.tencentcloudapi.com"

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = vpc_client.VpcClient(cred, "ap-shanghai-fsi", clientProfile)

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

                resp = client.DescribeSecurityGroupPolicies(req)
                #print(resp.to_json_string())
                stext = resp.to_json_string()
                if ip in  stext:
                        return True
                else:
                        return False
        except TencentCloudSDKException as err:
                print(err)

def checkDomainName(dname,ipList):
        ipPattern =  re.compile(r'(((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3})')
        ipPattern1 = re.compile(r'(Address: ((\d+.){3}(\d+)))')
        with os.popen('nslookup %s'%(dname)) as pipe:
                str_pipe = pipe.read()
                ip = ipPattern1.findall(str_pipe)
                for i in ip:
                        ipList.append(str(i[0]).split(":")[1].replace(" ",""))
def checkHostsFile(ipList,domainName):
        dhostList = []
        with os.popen('cat /etc/hosts') as hosts:
                str_hosts = hosts.read()
                dnamePattern = re.compile(r'((\d+.){3}(\d+))\s*(%s)' % (domainName))
                dhosts = dnamePattern.findall(str_hosts)
                for i in dhosts:
                    dhostList.append(i[0])
                dhosts1 = [ x for x in dhostList  if x in ipList]
                if len(dhosts) == 0:
                        os.system("echo %s  %s >>/etc/hosts"%(ipList[0],domainName))
                        print( "%s %s >>/etc/hosts"%(ipList[0],domainName))
                        return "NewInsert"
                if  len(dhosts1) != 0 :
                        return  True
                else:
                        os.system("sed -i '/%s/d' /etc/hosts"%(domainName))
                        os.system("echo \"%s  %s\" >>/etc/hosts"%(ipList[0],domainName) )
                        return "success update"

def CreateRoutes(appID,appKey,ip,domainName):
        try:
                cred = credential.Credential(appID, appKey)
                httpProfile = HttpProfile()
                httpProfile.endpoint = "vpc.ap-shanghai-fsi.tencentcloudapi.com"

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = vpc_client.VpcClient(cred, "ap-shanghai-fsi", clientProfile)

                req = models.CreateRoutesRequest()
                params = {
                        "Routes": [
                                {
                                        "DestinationCidrBlock": "%s"%(ip),
                                        "GatewayType": "NAT",
                                        "GatewayId": "nat",
                                        "RouteDescription": "%s"%(domainName)
                                }
                        ],
                        "RouteTableId": "rtb"
                }
                req.from_json_string(json.dumps(params))
                resp = client.CreateRoutes(req)
                print(resp.to_json_string())

        except TencentCloudSDKException as err:
                print(err)

def main():
        ipList = []
        checkDomainName(domainName,ipList)
        #checkHostsFile(ipList,domainName)
        for ip in ipList:
                print(ip)
                ipCheck = DescribeSecurityGroupPolicies(appID, appKey, SecurityGroupID,ip)
                if ipCheck:
                        pass
                else:
                        CreateSecurityGroupPolicies(appID, appKey, SecurityGroupID,Action,Protocol, Port, domainName,ip,cTime)
                        CreateRoutes(appID, appKey, ip, domainName)

if __name__ == '__main__':
        main()
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页