easy_whitelist 1.0.37__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ r"""Easy_whitelist is a smart tool that detects the local Internet IP address and automatically updates the local Internet IP address to the cloud security group whitelist. The tool is written in Python.
2
+ """
3
+ __version__ = '1.0.37'
4
+ # __author__ = 'qiqileleabaobao <qiqilelebaobao@163.com>'
5
+
6
+ __all__ = []
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import json
5
+ import os
6
+ import pprint
7
+ import string
8
+ import sys
9
+ import logging
10
+
11
+ from easy_whitelist.config import arg
12
+ from easy_whitelist.tcloud import client
13
+ from easy_whitelist.tcloud.template import list_template, set_template, create_template
14
+
15
+
16
+ def loop_list(common_client, proxy=None):
17
+ template_ids = list_template(common_client)
18
+ last_input = None
19
+ while True:
20
+ input_from_user = input('Please choose # template to set (or [L]ist or [Q]uit): ')
21
+ if last_input == '' and input_from_user == '':
22
+ break
23
+ last_input = input_from_user
24
+ if input_from_user.isdigit():
25
+ if template_ids:
26
+ if (a := int(input_from_user)) > 0 and a <= len(template_ids):
27
+ set_template(common_client, template_ids[a - 1], proxy)
28
+ else:
29
+ logging.info('Wrong index, please input right index from the list.')
30
+ elif input_from_user == 'l' or input_from_user == 'L':
31
+ list_template(common_client)
32
+ elif input_from_user == 'q' or input_from_user == 'Q':
33
+ break
34
+ elif input_from_user == '':
35
+ continue
36
+ else:
37
+ logging.info('Input error.')
38
+
39
+ def set_log(verbose=0):
40
+ # FMT = '%(asctime)s %(process)d %(filename)s L%(lineno)s %(levelname)s %(message)s'
41
+ FMT = '%(asctime)s - %(process)d - %(filename)s - L%(lineno)s - %(levelname)s - %(message)s'
42
+
43
+ if verbose == 0:
44
+ logging.basicConfig(level=logging.WARN, format=FMT)
45
+ elif verbose == 1:
46
+ logging.basicConfig(level=logging.INFO, format=FMT)
47
+ elif verbose >=2:
48
+ logging.basicConfig(level=logging.DEBUG, format=FMT)
49
+ else:
50
+ print("Wrong position in set_log.")
51
+
52
+ def main():
53
+ tencent, alibaba, action, target, target_id, proxy, verbose = arg.init_arg()
54
+
55
+ set_log(verbose)
56
+
57
+ common_client = client.get_common_client(proxy)
58
+
59
+ if tencent and target == 'template':
60
+ if action == 'list':
61
+ loop_list(common_client)
62
+ elif action == 'set':
63
+ set_template(common_client, target_id, proxy)
64
+ elif action == 'create':
65
+ create_template(common_client, target_id, proxy)
66
+ else:
67
+ logging.error('Wrong postion, shall not be here.')
68
+
69
+
70
+ if __name__ == '__main__':
71
+ main()
@@ -0,0 +1,2 @@
1
+
2
+ __all__ = ['arg']
@@ -0,0 +1,21 @@
1
+ import argparse
2
+
3
+ def init_arg():
4
+ '''parse parameter from command line.'''
5
+
6
+ parser = argparse.ArgumentParser(prog='easy', description='This is a cloud acl auto whitelist tool.', epilog='Enjoy the tool. :) ')
7
+
8
+ my_group = parser.add_mutually_exclusive_group(required=False)
9
+ my_group.add_argument('-t', '-T', '--tencent', action='store_true', default=True, help='tencent cloud')
10
+ my_group.add_argument('-a', '-A', '--alibaba', action='store_true', help='alibaba cloud')
11
+
12
+ parser.add_argument('-p', '-P', '--proxy', action='store', default=None, type=int, help ='local HTTP proxy port')
13
+ parser.add_argument('-v', '--verbose', action='count', default=0)
14
+
15
+ parser.add_argument('target', help='template or rule_id', choices=['template', 'rule_id'])
16
+ parser.add_argument('action', help='list', choices=['list', 'set', 'create'])
17
+ parser.add_argument('target_id', help='template id or rule id', nargs='?')
18
+
19
+ args = parser.parse_args()
20
+
21
+ return args.tencent, args.alibaba, args.action, args.target, args.target_id, args.proxy, args.verbose
File without changes
@@ -0,0 +1,5 @@
1
+
2
+ safari_user_ageent = ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15']
3
+ chrome_user_agent = ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36']
4
+ edge_user_agent = ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0']
5
+ curl_user_agent = ['curl/8.6.0', 'curl/7.29.0']
@@ -0,0 +1,70 @@
1
+ import requests
2
+ import sys
3
+ import random
4
+ import re
5
+ import time
6
+ import logging
7
+
8
+ from . import url
9
+
10
+ def get_local_ip_from_url_and_parse(u, patt, ag, proxy=None):
11
+ # 发送GET请求
12
+ headers = {'user-agent': ag}
13
+ try:
14
+ logging.info(f'Starting fetch local ip from {u} with proxy {proxy}')
15
+
16
+ if proxy:
17
+ response = requests.get(u, headers=headers, timeout=(3,5),
18
+ proxies={"http": f"http://127.0.0.1:{proxy}",
19
+ "https": f"http://127.0.0.1:{proxy}"
20
+ })
21
+ else:
22
+ response = requests.get(u, headers=headers, timeout=(3, 5))
23
+
24
+ # 获取响应内容
25
+ respon = response.text
26
+ l_ip = url.parse_ip_from_response(respon, patt)
27
+ logging.info(f'Ending fetch local ip from {u} with ip {l_ip}')
28
+
29
+ return l_ip
30
+ except Exception as e:
31
+ logging.error(e)
32
+ return None
33
+
34
+ def validate_ip(l_ip):
35
+ if not l_ip:
36
+ return False
37
+
38
+ # r'(?:(?:25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[1]?[0-9][0-9]?)'
39
+ # r'(?:\d{1,3}\.){3}\d{1,3}'
40
+ # r'((?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])'
41
+ # r'(?<![\.\d])(?:25[0-5]\.|2[0-4]\d\.|[01]?\d\d?\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![\.\d])'
42
+ pat = r'((?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])'
43
+ if re.fullmatch(pat, l_ip):
44
+ return True
45
+ else:
46
+ return False
47
+
48
+ def get_local_ips(proxy=None):
49
+ ip_list = []
50
+ for i, u in enumerate(url.detect_url, 1):
51
+ l_ip = get_local_ip_from_url_and_parse(u[0], u[1], u[2], proxy)
52
+ if l_ip and validate_ip(l_ip):
53
+ ip_list.append(l_ip)
54
+ return ip_list
55
+
56
+ def print_ip_list(ip_list):
57
+ number = 100
58
+ print(f'{"Detected Local IP List":=^{number}}\n'
59
+ f'{"#":<38}IP Address\n'
60
+ f'{"-" * number}'
61
+ )
62
+
63
+ for i, ip in enumerate(ip_list, 1):
64
+ print(f'{str(i):<38}{ip}')
65
+
66
+ print('-' * number)
67
+
68
+
69
+ if __name__ == '__main__':
70
+ print(validate_ip('1.0.0.0'))
@@ -0,0 +1,4 @@
1
+
2
+ IFCONFIG_ME_PATTERN = r'(.+)'
3
+ CIP_CC_PATTERN = r'URL\s+?:\s+?http://www.cip.cc/(.+)'
4
+ TOOL_LU_PATTERN = r'<p>你的外网IP地址是:\s*?(.+)</p>'
@@ -0,0 +1,16 @@
1
+ import re
2
+ import random
3
+
4
+ from .agent import *
5
+ from .pattern import *
6
+
7
+
8
+ def parse_ip_from_response(response, patt):
9
+ if result:=re.search(patt, response):
10
+ return result.group(1)
11
+
12
+ detect_url = [
13
+ ['https://ifconfig.me', IFCONFIG_ME_PATTERN, random.choice(curl_user_agent)],
14
+ ['http://cip.cc', CIP_CC_PATTERN, random.choice(chrome_user_agent)],
15
+ ['https://tool.lu/ip/', TOOL_LU_PATTERN, random.choice(chrome_user_agent)]
16
+ ]
@@ -0,0 +1,45 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2017-2021 Tencent Ltd.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import os
16
+ import json
17
+
18
+ from tencentcloud.common.common_client import CommonClient
19
+ from tencentcloud.common import credential
20
+ from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
21
+ from tencentcloud.common.profile.client_profile import ClientProfile
22
+ from tencentcloud.common.profile.http_profile import HttpProfile
23
+
24
+ try:
25
+ cred = credential.Credential(
26
+ os.environ.get("TENCENTCLOUD_SECRET_ID"),
27
+ os.environ.get("TENCENTCLOUD_SECRET_KEY"))
28
+
29
+ httpProfile = HttpProfile()
30
+ # 域名首段必须和下文中CommonClient初始化的产品名严格匹配
31
+ httpProfile.endpoint = "cvm.tencentcloudapi.com"
32
+ clientProfile = ClientProfile()
33
+ clientProfile.httpProfile = httpProfile
34
+
35
+ # common client方法支持指定header,如 X-TC-TraceId、X-TC-Canary
36
+ headers = {
37
+ "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca"
38
+ }
39
+
40
+ # 实例化要请求的common client对象,clientProfile是可选的。
41
+ common_client = CommonClient("cvm", '2017-03-12', cred, "ap-nanjing", profile=clientProfile)
42
+ # 接口参数作为json字典传入,得到的输出也是json字典,请求失败将抛出异常,headers为可选参数
43
+ print(common_client.call_json("DescribeInstances", {"Limit": 10}, headers=headers))
44
+ except TencentCloudSDKException as err:
45
+ print(err)
@@ -0,0 +1,75 @@
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import sys
4
+ import logging
5
+
6
+ from tencentcloud.common import credential
7
+ from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
8
+ # 导入对应产品模块的client models。
9
+ from tencentcloud.cvm.v20170312 import cvm_client, models
10
+
11
+ # 导入可选配置类
12
+ from tencentcloud.common.profile.client_profile import ClientProfile
13
+ from tencentcloud.common.profile.http_profile import HttpProfile
14
+ try:
15
+ # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey。
16
+ # 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中,请参考本文凭证管理章节。
17
+ # 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
18
+ # cred = credential.Credential("secretId", "secretKey")
19
+ cred = credential.Credential(
20
+ os.environ.get("TENCENTCLOUD_SECRET_ID"),
21
+ os.environ.get("TENCENTCLOUD_SECRET_KEY"))
22
+ cred = credential.Credential("SecretId", "SecretKey")
23
+
24
+ # 实例化一个http选项,可选的,没有特殊需求可以跳过。
25
+ httpProfile = HttpProfile()
26
+ # 如果需要指定proxy访问接口,可以按照如下方式初始化hp
27
+ # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口")
28
+ httpProfile.protocol = "https" # 在外网互通的网络环境下支持http协议(默认是https协议),建议使用https协议
29
+ httpProfile.keepAlive = True # 状态保持,默认是False
30
+ httpProfile.reqMethod = "GET" # get请求(默认为post请求)
31
+ httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒)
32
+ httpProfile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" # 指定接入地域域名(默认就近接入)
33
+
34
+ # 实例化一个client选项,可选的,没有特殊需求可以跳过。
35
+ clientProfile = ClientProfile()
36
+ clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法
37
+ clientProfile.language = "en-US" # 指定展示英文(默认为中文)
38
+ clientProfile.httpProfile = httpProfile
39
+
40
+ # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
41
+ client = cvm_client.CvmClient(cred, "ap-shanghai", clientProfile)
42
+
43
+ # 打印日志按照如下方式,也可以设置log_format,默认为 '%(asctime)s %(process)d %(filename)s L%(lineno)s %(levelname)s %(message)s'
44
+ # client.set_stream_logger(stream=sys.stdout, level=logging.DEBUG)
45
+ # client.set_file_logger(file_path="/log", level=logging.DEBUG) 日志文件滚动输出,最多10个文件,单个文件最大512MB
46
+ # client.set_default_logger() 去除所有log handler,默认不输出
47
+
48
+ # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
49
+ req = models.DescribeInstancesRequest()
50
+
51
+ # 填充请求参数,这里request对象的成员变量即对应接口的入参。
52
+ # 您可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义。
53
+ respFilter = models.Filter() # 创建Filter对象, 以zone的维度来查询cvm实例。
54
+ respFilter.Name = "zone"
55
+ respFilter.Values = ["ap-shanghai-1", "ap-shanghai-2"]
56
+ req.Filters = [respFilter] # Filters 是成员为Filter对象的列表
57
+
58
+ # python sdk支持自定义header如 X-TC-TraceId、X-TC-Canary,可以按照如下方式指定,header必须是字典类型的
59
+ headers = {
60
+ "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca"
61
+ }
62
+ req.headers = headers
63
+
64
+ # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的,headers为可选参数。
65
+ # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
66
+ resp = client.DescribeInstances(req)
67
+
68
+ # 输出json格式的字符串回包
69
+ print(resp.to_json_string(indent=2))
70
+
71
+ # 也可以取出单个值。
72
+ # 您可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义。
73
+ print(resp.TotalCount)
74
+ except TencentCloudSDKException as err:
75
+ print(err)
@@ -0,0 +1,20 @@
1
+ import os
2
+ from tencentcloud.common import credential
3
+ from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
4
+ from tencentcloud.cvm.v20170312 import cvm_client, models
5
+
6
+ try:
7
+ # 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中,请参考本文凭证管理章节。
8
+ # 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
9
+ # cred = credential.Credential("secretId", "secretKey")
10
+ cred = credential.Credential(
11
+ os.environ.get("TENCENTCLOUD_SECRET_ID"),
12
+ os.environ.get("TENCENTCLOUD_SECRET_KEY"))
13
+ client = cvm_client.CvmClient(cred, "ap-nanjing")
14
+
15
+ req = models.DescribeInstancesRequest()
16
+ resp = client.DescribeInstances(req)
17
+
18
+ print(resp.to_json_string())
19
+ except TencentCloudSDKException as err:
20
+ print(err)
File without changes
@@ -0,0 +1,26 @@
1
+ import os
2
+
3
+ from tencentcloud.common import credential
4
+ from tencentcloud.common.profile.http_profile import HttpProfile
5
+ from tencentcloud.common.profile.client_profile import ClientProfile
6
+ from tencentcloud.common.common_client import CommonClient
7
+
8
+
9
+ def get_common_client(proxy):
10
+ # cred = credential.Credential(
11
+ # os.environ.get("TENCENTCLOUD_SECRET_ID"),
12
+ # os.environ.get("TENCENTCLOUD_SECRET_KEY"))
13
+
14
+ cred = credential.DefaultCredentialProvider().get_credential()
15
+
16
+ httpProfile = HttpProfile()
17
+ # httpProfile.endpoint = "vpc.tencentcloudapi.com"
18
+ httpProfile.proxy = f'127.0.0.1:{proxy}' if proxy else None
19
+
20
+ clientProfile = ClientProfile()
21
+ clientProfile.httpProfile = httpProfile
22
+ # clientProfile.signMethod = 'HmacSHA256'
23
+
24
+ common_client = CommonClient("vpc", "2017-03-12", cred, "ap-nanjing", profile=clientProfile)
25
+
26
+ return common_client
@@ -0,0 +1,157 @@
1
+ import json
2
+ import random
3
+ import sys
4
+ import logging
5
+
6
+ from ..ip import ip
7
+ from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
8
+
9
+
10
+ def write_template_list_to_temp_file(template_ids):
11
+
12
+ with open('/tmp/template_0000.txt', 'w') as temp_file:
13
+ json.dump(template_ids, temp_file)
14
+
15
+ return temp_file.name
16
+
17
+ def get_template(common_client):
18
+ try:
19
+ params = {}
20
+ # templates = common_client.call_json("DescribeAddressTemplates", params, options = {'SkipSign': True})
21
+ templates = common_client.call_json("DescribeAddressTemplates", params, )
22
+ return templates
23
+
24
+ except TencentCloudSDKException as err:
25
+ print(err)
26
+ return None
27
+
28
+ def list_template(common_client):
29
+ number = 150
30
+ print(f'{"Tencent Cloud Template List":=^{number}}\n' \
31
+ f'{"#":<10}{"Template ID":<20}{"CreatedTime":<30}{"Addresses":<60}{"AddressTemplateName":<30}\n' \
32
+ f'{"-" * number}'
33
+ )
34
+
35
+ template_ids = []
36
+ if not(templates := get_template(common_client)):
37
+ return template_ids
38
+
39
+ for i, template in enumerate(templates['Response']['AddressTemplateSet'], 1):
40
+ template_ids.append(template['AddressTemplateId'])
41
+ # print(template_ids)
42
+ addreset = ' ~ '.join(template['AddressSet'][:3])
43
+ if len(template['AddressSet']) > 3:
44
+ addreset += f' ~~~ {len(template["AddressSet"])-3} more...'
45
+ print(f"{str(i):10}"
46
+ f"{template['AddressTemplateId']:20}"
47
+ f"{template['CreatedTime']:30}"
48
+ f"{addreset:<60}"
49
+ f"{template['AddressTemplateName']:30}"
50
+ )
51
+ print('-' * number)
52
+
53
+ # write_template_list_to_temp_file(template_ids)
54
+
55
+ return template_ids
56
+
57
+ def format_addres_extra_string_from_list(client_ips):
58
+ cs = '"AddressesExtra":['
59
+ for client_ip in client_ips:
60
+ cs += '{{"Address":"{}","Description":"client_ip"}},'.format(client_ip)
61
+ cs_format = cs.rstrip(',')
62
+ cs_format += ']'
63
+
64
+ return cs_format
65
+
66
+ def modify_template_address(common_client, client_ips, target_id):
67
+
68
+ if not target_id:
69
+ return False
70
+
71
+ # 增加描述校验,避免更改错误
72
+ params = f"{{\"Filters\":[{{\"Name\":\"address-template-id\",\"Values\":[\"{target_id}\"]}}]}}"
73
+ try:
74
+ respon = common_client.call_json("DescribeAddressTemplates", json.loads(params))
75
+ if (TemplateSet := respon['Response']['AddressTemplateSet']) and \
76
+ TemplateSet[0]['AddressTemplateName'].startswith('temp-open-'):
77
+ # print(respon)
78
+ pass
79
+ else:
80
+ print('This is not a template generated from this tool. Shall not be modified.')
81
+ return False
82
+ except (TencentCloudSDKException, IndexError) as err:
83
+ # IndexError catch when there is no match target.Example: 'AddressTemplateSet': []
84
+ print(f"{err=}, {type(err)=}")
85
+ sys.exit(1)
86
+
87
+ params = "{{\"AddressTemplateId\":\"{}\",{}}}".format(target_id, client_ips)
88
+ try:
89
+ respon = common_client.call_json("ModifyAddressTemplateAttribute", json.loads(params))
90
+ # print(respon)
91
+ # print('-' * 100)
92
+ except TencentCloudSDKException as err:
93
+ print(f"Unexpected {err=}, {type(err)=}")
94
+ return False
95
+
96
+ return True
97
+
98
+ def get_local_ip_and_format_addressesextra(proxy=None):
99
+ client_ip_list = ip.get_local_ips(proxy)
100
+ # ip.print_ip_list(client_ip_list)
101
+ client_ip_list = list(set(client_ip_list))
102
+ addresses_extra = format_addres_extra_string_from_list(client_ip_list)
103
+
104
+ return addresses_extra
105
+
106
+ def set_template(common_client, target_id, proxy=None):
107
+ # with open('/tmp/template_0000.txt', 'r') as temp_file:
108
+ # data = json.load(temp_file)
109
+ # print(data)
110
+ if target_id:
111
+ if target_id.startswith('ipm-'):
112
+ addresses_extra = get_local_ip_and_format_addressesextra(proxy)
113
+ if modify_template_address(common_client, addresses_extra, target_id):
114
+ logging.info(f'Successfully set {{{target_id}}} to {{{addresses_extra}}}')
115
+ else:
116
+ logging.warning('Wrong template id.')
117
+ else:
118
+ logging.error('Set template shall input template id.')
119
+
120
+ def create_template(common_client, rule_id, proxy=None):
121
+
122
+ if not rule_id:
123
+ print('Create template shall input security group id.')
124
+ return False
125
+
126
+ params = "{}"
127
+ try:
128
+ templates = []
129
+ respon = common_client.call_json("DescribeAddressTemplates", json.loads(params))
130
+ print(json.dumps(respon, ensure_ascii=False))
131
+ for template in respon['Response']['AddressTemplateSet']:
132
+ if template['AddressTemplateName'].startswith('temp-open-'):
133
+ templates.append((template['AddressTemplateId'], template['AddressTemplateName'], template['CreatedTime']))
134
+ if templates:
135
+ print(f'Already have template without creation: {templates}')
136
+ return True
137
+
138
+ except TencentCloudSDKException as err:
139
+ print(f"{err=}, {type(err)=}")
140
+ return False
141
+
142
+ addresses_extra = get_local_ip_and_format_addressesextra(proxy)
143
+ params = f"{{\"AddressTemplateName\":\"temp-open-{random.randint(1,9999):04d}\",{addresses_extra}}}"
144
+ try:
145
+ respon = common_client.call_json("CreateAddressTemplate", json.loads(params))
146
+ print(json.dumps(respon, ensure_ascii=False))
147
+
148
+ if template_id := respon['Response']['AddressTemplate']['AddressTemplateId']:
149
+ params = f"{{\"SecurityGroupId\":\"{rule_id}\",\"SecurityGroupPolicySet\":{{\"Ingress\":[{{\"PolicyIndex\":0,\"Protocol\":\"ALL\",\"AddressTemplate\":{{\"AddressId\":\"{template_id}\"}},\"Action\":\"accept\",\"PolicyDescription\":\"temp-open\"}}]}}}}"
150
+ respon = common_client.call_json("CreateSecurityGroupPolicies", json.loads(params))
151
+ print(json.dumps(respon))
152
+
153
+ except TencentCloudSDKException as err:
154
+ print(f"{err=}, {type(err)=}")
155
+ return False
156
+
157
+ return True
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) qiqilelebaobao
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: easy_whitelist
3
+ Version: 1.0.37
4
+ Summary: Easy_whitelist is a smart tool that detects the local Internet IP address and automatically updates the local Internet IP address to the cloud security group whitelist. The tool is written in Python.
5
+ Keywords: automation,whitelist,acl,security-groups,alibaba-cloud,tencent-cloud,security-tools,security-group-rule
6
+ Author: qiqilelebaobao
7
+ Author-email: qiqilelebaobao <qiqilelebaobao@163.com>
8
+ Maintainer-email: qiqilelebaobao <qiqilelebaobao@163.com>
9
+ Requires-Python: >= 3.6
10
+ Description-Content-Type: text/markdown
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.6
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Requires-Dist: tencentcloud-sdk-python
24
+ Requires-Dist: rich ; extra == "cli"
25
+ Requires-Dist: click ; extra == "cli"
26
+ Requires-Dist: PyQt5 ; extra == "gui"
27
+ Project-URL: Homepage, https://github.com/qiqilelebaobao/easy_whitelist
28
+ Provides-Extra: cli
29
+ Provides-Extra: gui
30
+
31
+ # Easy_whitelist
32
+
33
+ Easy_whitelist 是一个探测本机互联网 IP 地址,将并本机互联网IP地址,自动更新到云安全组白名单的小工具。工具使用 Python 编写。
34
+
35
+ Easy_whitelist is a smart tool that detects the local Internet IP address and automatically updates the local Internet IP address to the cloud security group whitelist. The tool is written in Python.
36
+
37
+ 主要功能包括:
38
+ * 自动探测本机互联网 IP 地址
39
+ * 支持阿里云、腾讯云的安全组白名单更新
40
+ * 腾讯云支持地址模板更新
41
+
42
+ Main functions include:
43
+ * Automatically detect the local Internet IP address
44
+ * Support security group whitelist updates for Alibaba Cloud and Tencent Cloud
45
+ * Tencent Cloud supports address template updates
46
+
47
+ ## 适用场景 Applicable Scenarios
48
+
49
+ * 场景一:不知道如何探测本机的公网IP的用户,通过本工具自动探测公网 IP,并添加云安全组白名单
50
+ * 场景二:IP 地址因为 NAT 环境经常变化,包括家庭环境或者公司无固定出口 IP 的宽带环境,需要安全的使用云环境资源
51
+ * 场景三:测试场景,频繁变换客户端环境,需要安全的使用云环境资源
52
+
53
+ * Scene1: Users who do not know how to detect the public IP of their local machine can use this tool to automatically detect the public IP and add it to the cloud security group whitelist
54
+ * Scene2: IP addresses often change due to NAT environments, including home environments or broadband environments without fixed export IPs in companies, which require safe use of cloud environment resources
55
+ * Scene3: Test scenarios, frequent changes in client environments, which require safe use of cloud environment resources
56
+
57
+ ## 安装指南 Installation Guide
58
+
59
+ 需要 Python3 环境
60
+ Python3 is required
61
+
62
+ ## 使用说明 Basic Usage
63
+
64
+ * 通过列表选择模版,设置白名单
65
+ ```shell
66
+ $ easy template list
67
+ ```
68
+
69
+ * 通过新创建模版,设置白名单。需要指定关联的安全组ID
70
+ ```shell
71
+ $ easy template create rule_id
72
+ ```
73
+
@@ -0,0 +1,20 @@
1
+ easy_whitelist/__init__.py,sha256=-_Ol4PAr-2Ekzao3hvp8PQKj9ONjEDSDbPmG6m_F0us,303
2
+ easy_whitelist/__main__.py,sha256=x5teqF_1OWhLujmBM37jYNJ9Ed1kF_xyzkYpJf4TCI0,2358
3
+ easy_whitelist/config/__init__.py,sha256=fK-lJ3GD4u1_FGkZfPf-f7fxjMwb1t0AZcG7mfIHLks,19
4
+ easy_whitelist/config/arg.py,sha256=efzlQSHK49MFhf0VAnVt6jkGxdwW3ae3yUJmDIKx9mY,1087
5
+ easy_whitelist/ip/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ easy_whitelist/ip/agent.py,sha256=dJDkw1mipazcOyldbBZW5Mhjr17UqDlaBn2jUo80C7I,487
7
+ easy_whitelist/ip/ip.py,sha256=K34xjZsFWsSi70crQQ51k04x8H5StC-yE5ZMWDEm41I,2145
8
+ easy_whitelist/ip/pattern.py,sha256=184XTlT0087eBZbm9LC5AB38PMLazQueW8E7l4jSwkM,149
9
+ easy_whitelist/ip/url.py,sha256=kFBZ2E_AYQ-AYo7eeKQJ22kjviQ61bZMdQS4EOR5j-k,439
10
+ easy_whitelist/sample/common_client_sample.py,sha256=kPde6JHuGLHapC7oSzoC_RdjS7Lxpqtp890NbGIVomc,1958
11
+ easy_whitelist/sample/cvm_sample_detail.py,sha256=sxsDJY2YvU6uwgbGBzWrl4tFZOKjGq9YMVEKIEjUNEI,4144
12
+ easy_whitelist/sample/cvm_sample_simple.py,sha256=g5rESUuRwcVqxemPct3QrWhZ4tnoRHh_hFkrqlHOTw0,871
13
+ easy_whitelist/tcloud/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ easy_whitelist/tcloud/client.py,sha256=eHevgHB1Y8C2Rwa8ztiIm-GkNTOJDlWU7RMNhw6oTmw,906
15
+ easy_whitelist/tcloud/template.py,sha256=NQzYPM67tMlILG5Q4AzNjOBlRKqaypTk36M1xzJE7fU,6053
16
+ easy_whitelist-1.0.37.dist-info/entry_points.txt,sha256=-URzXdGXqVTDQm_AhH9k0u4Qm9G0s4ZDXcnA-XQt73Q,53
17
+ easy_whitelist-1.0.37.dist-info/LICENSE,sha256=sWhlh6jzXRpuhxIbCZfjCEX_YQI4mMK6iO1bfpgkfzM,11343
18
+ easy_whitelist-1.0.37.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
19
+ easy_whitelist-1.0.37.dist-info/METADATA,sha256=uDHpIdNnRujAyZslmfH41QSkFsA116p55vUMAvW24P8,3478
20
+ easy_whitelist-1.0.37.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ easy=easy_whitelist.__main__:main
3
+