简介
双11活动买了台腾讯云服务器,个人使用,想实现一个简单的安全访问策略。
考虑过以前做的 nginx+lua 代理,也临时上过我做的那个 golang 实现的 udp 敲门策略。
最终还是觉得维护起来麻烦,用云厂商的安全组功能就够了。
原理
服务器安全组只对1个IP开放 全部端口。
笔记本电脑上设置一个开机任务,每次开启检查一下自己的公网出口IP有无变化,有变化就调用腾讯云的接口更新一下安全组的策略。
使用腾讯云SDK修改安全组策略
这个示例只是对已有安全组策略中的某一条策略进行修改,熟悉接口后配合应用程序可以做成针对某IP进行拦截。
详细规则可以去看官方的API文档
https://cloud.tencent.com/document/api
本例使用的是 python, 实际官方对主流编程语言都提供SDK,反正都是http请求,熟悉接口后就算使用 curl 也是可以的;
简单流程描述
-
登录控制台,获取 SecretId 和 SecretKey 信息,默认没有的需要手动启用。
-
在控制台找到你的安全组,记住 所在区域 和 安全组的ID
区域就是 ap-<地址位置拼音>,如 ap-shanghai,
安全组的ID,就在安全组信息的第一列,如 sg-ccms23e2,
记住你要修改的ID在哪一行,最后一行的 PolicyIndex 值是 0,往上+1;
-
安装 sdk, 我使用的是 python 的 SDK
pip install –upgrade tencentcloud-sdk-python
-
制作脚本,后面网络发生变化后,就运行一下这个脚本
附当前使用的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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Email:
# DateTime: 2021-11-20 05:37:43
__author__ = 'chenxu'
import json
import re
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 requests
def getIntelenetIP():
'''获取当前电脑的出网公网地址'''
url = "http://txt.go.sohu.com/ip/soip"
try:
r = requests.get(url)
if r.status_code != 200:
print('get ip address error')
exit()
ip = re.findall(r'\d+.\d+.\d+.\d+',r.text)[0]
except Exception as err:
print(err)
exit()
return ip
def ReplaceSecurityGroupPolicy(ip):
SecretId = 'xxxxx' # 替换
SecretKey = 'xxxxx' # 替换
Region = 'ap-shanghai' # 更换为所在区域
SecurityGroupId = 'sg-ccms23e2' # 更换为安全组的ID
Port = '39021' # 要调整安全组规则的那个端口号
try:
cred = credential.Credential(SecretId, SecretKey)
httpProfile = HttpProfile()
httpProfile.endpoint = "vpc.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = vpc_client.VpcClient(cred, Region, clientProfile)
req = models.ReplaceSecurityGroupPolicyRequest()
params = {
"SecurityGroupId": SecurityGroupId,
"SecurityGroupPolicySet": {
"Ingress": [
{
"PolicyIndex": 0, # 就是安全组内已有的哪一条策略,最后一条是0,往上就+1
"Protocol": "tcp", # 什么协议
"Port": Port, # 变量,需要修改的端口
"CidrBlock": ip, # 变量,需要修改的IP
"Action": "ACCEPT", # 允许
"PolicyDescription": "test2" # 备注
}
]
}
}
req.from_json_string(json.dumps(params))
resp = client.ReplaceSecurityGroupPolicy(req)
print(resp.to_json_string())
print(f'add {ip} to SecurityGroup Success')
except TencentCloudSDKException as err:
print(err)
ip = getIntelenetIP()
ReplaceSecurityGroupPolicy(ip)
|
