腾讯云自动化添加安全组

一般登陆云服务器都限制来源 IP,添加白名单较为繁琐,通过接口可以快速添加。

# ./addWhiteIP

{"Response":{"RequestId":"c89ddf9df-738c-4f2a-9f02-dcd3cfe8c852"}}
Outer IP : 106.224.145.147
1
2
3
4

前置项

在腾讯云用户管理页面创建一个用于操作私有网络(VPC)的权限

  • 访问方式:编程访问
  • 用户权限:QcloudVPCFullAccess

-w1796

1. 创建参数模板,在安全组中引用

直接用 API 频繁修改安全组存在风险,我们可以将参数模板新窗口打开作为安全组中的一行。

-w1758

安全组新窗口打开中引用即可。

-w1733

2. 准备代码

请参照 腾讯云的 API explorer新窗口打开 生成对应的代码。

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	vpc "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vpc/v20170312"
)

// VPC 中添加 IP组的方式管理安全组

func main() {

	credential := common.NewCredential(
		"<SecretId>",  // 请替换为你的腾讯云 SecretId
		"<SecretKey>", // 请替换为你的腾讯云 SecretKey
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "vpc.tencentcloudapi.com"
	client, _ := vpc.NewClient(credential, "<Region>", cpf) // 请替换为可用区ID,例如 ap-guangzhou

	request := vpc.NewModifyAddressTemplateAttributeRequest()

    // 获取IPv4地址:https://4.ipw.cn
	// 获取IPv6地址:https://6.ipw.cn
	// 确认用户网络是IPv4还是IPv6访问优先:https://test.ipw.cn/api/ip/myip?json
	responseClient, errClient := http.Get("https://4.ipw.cn") // 获取外网 IP
	if errClient != nil {
		fmt.Printf("获取外网 IP 失败,请检查网络\n")
		panic(errClient)
	}
	// 程序在使用完 response 后必须关闭 response 的主体。
	defer responseClient.Body.Close()

	body, _ := ioutil.ReadAll(responseClient.Body)

	clientIP := string(body)
	params := fmt.Sprintf("{\"AddressTemplateId\":\"<AddressTemplateId>\",\"Addresses\":[\"%s\"]}", clientIP) // 请将 AddressTemplateId 替换为参数模板 ID
	err := request.FromJsonString(params)
	if err != nil {
		panic(err)
	}
	response, err := client.ModifyAddressTemplateAttribute(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", response.ToJsonString())
	fmt.Printf("\nOuter IP : %s\n", clientIP)

}
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

3. 编译

# go build addWhiteIP.go
# ./addWhiteIP
{"Response":{"RequestId":"ec9d18dc-cfcf-4f0b-a0c0-02a9c212dcxx"}}
Outer IP : xx.xx.xx.xx
1
2
3
4

reference

IPv6工具箱 小程序 和 iOS App

小程序

微信扫一扫,唤起小程序

IPv6工具箱微信小程序

你也可以复制小程序短链接,发送给任意一个微信好友,在聊天对话框中打开该短链接即可唤起小程序。

#小程序://IPv6工具箱/U1R4edQusuF2zpa
1

注:如果你觉得这个小程序还不错,欢迎在微信搜一搜中搜索 IPv6工具箱 并给予评价,你的鼓励是本站前进的动力😘!

苹果 iOS App

如果你正在使用 iPhone 打开本站,可点击 IPv6工具箱新窗口打开 快速进入 App Store 下载 App,当然你也可以使用微信扫描下方二维码。

IPv6工具箱 App

注:如果你觉得这个 App 还不错,欢迎在 App Store新窗口打开 轻点评分+评论,你的鼓励是本站前进的动力!😘

访客IP: ,您的网络 访问优先