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

简介

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

脚本

需要安装腾讯SDK环境

1
pip install --upgrade tencentcloud-sdk-python

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

水平有限,请见谅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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()

Python_动态解析域名更换安全组规则
https://imwang77.github.io/2020/12/04/Python_动态解析域名更换安全组/
作者
imwang77
发布于
2020年12月4日
更新于
2021年5月28日
许可协议