重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

go更新腾讯云DNSPod的解析记录

纯粹练手用的,大家轻喷

站在用户的角度思考问题,与客户深入沟通,找到天河网站设计与天河网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站建设、成都网站设计、企业官网、英文网站、手机端网站、网站推广、域名注册虚拟主机、企业邮箱。业务覆盖天河地区。

  1. 获取SecretId,SecretKey
    打开腾讯云,登录之后打开https://console.cloud.tencent.com/cam/capi,然后新建密钥记录生成的SecretId,SecretKey
  2. 获取RecordId
    然后打开https://console.cloud.tencent.com/api/explorer?Product=dnspod&Version=2021-03-23&Action=DescribeRecordList&SignVersion=点击在线调试,然后将自己的域名输入到Domain下面的框里,点击发送请求,此时会让扫码登录,微信扫码登录即可,登录之后在响应结果框里会出现自己的RecordId,记录一下自己需要修改的RecordId
  3. 添加一个dnspodRecord.go文件
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/robfig/cron"
	"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"
	dnspod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v"
)
//全局IP,本次获取与上次作比较,相同IP不需要更新
var currentIp = ""

func main() {
	c := cron.New()
	spec := "*/30 * * * * ?" //可自行更改,默认是30秒执行一次
	c.AddFunc(spec, func() {
		fmt.Printf("start:%v \n", time.Now())
		modifyRecordAfterGetIp()
		fmt.Printf("shop:%v \n", time.Now())
	})
	c.Start()

	select {}
}
//循环获取公网IP,对比变化,变化后同步
func modifyRecordAfterGetIp() {
	fmt.Printf("currentIp: %s \n", currentIp)
	//获取记录
	records := [][]string{}
	row1 := []string{"yourhost.cn", "A", "yourRecordId", "默认", "", "*"}
	row2 := []string{"yourhost.cn", "A", "yourRecordId", "默认", "", "@"}
	row3 := []string{"yourhost.cn", "A", "yourRecordId", "默认", "", "www"}
	records = append(records, row1)
	records = append(records, row2)
	records = append(records, row3)

	//获取Ip的网址
	sliceIp := []string{"myip.ipip.net/s", "api.ip.sb/ip", "ident.me", "ip.3322.net", "ip.cip.cc", "api.ipify.org"}
	// 迭代每一个元素,获取Ip并判断Ip是否符合,再调用修改腾讯云记录
	for index, value := range sliceIp {
		fmt.Printf("---- 开始请求IP %s ----\n", value)
		result := string(getIp("http://" + value))
		isIpv4 := matchIpv4(result)
		fmt.Printf("Index: %d Value: %s result:%s matchIpv4:%t \n", index, value, result, isIpv4)
		if isIpv4 {
			if currentIp != result {
				fmt.Printf("---- 结束请求IP ----\n \n")
				currentIp = result
				var i int
				for i = 0; i < 3; i++ {
					intNum, _ := strconv.Atoi(records[i][2])
					modifyDynamicDNS(records[i][0], records[i][1], uint64(intNum), records[i][3], currentIp, records[i][5])
				}
				fmt.Printf("currentIp: %s \n", currentIp)
			}
			fmt.Printf("Ip未发生变化 \n")
			break
		}
	}
	fmt.Printf("---- 结束 ---- \n")
	fmt.Printf("currentIp: %s \n", currentIp)
}

//调用腾讯云api修改记录
func modifyDynamicDNS(domain string, recordType string, recordId uint64, recordLine string, ip string, subDomain string) {
	credential := common.NewCredential(
		"yourSecretId",
		"yourSecretKey",
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "dnspod.tencentcloudapi.com"
	client, _ := dnspod.NewClient(credential, "", cpf)

	request := dnspod.NewModifyRecordBatchRequest()

	request.RecordIdList = make([]*uint64, 1)

	fmt.Printf("开始更新记录:%d  \n", recordId)

	request.RecordIdList[0] = &recordId

	request.Change = new(string)
	request.ChangeTo = new(string)

	*request.Change = "value"
	*request.ChangeTo = strings.Replace(ip, "\n", "", -1)

	fmt.Printf("requestJson:%s  \n", request.ToJsonString())
	response, err := client.ModifyRecordBatch(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("error:An API error has returned: %s \n", err)
		return
	}
	if err != nil {
		panic(err)
	}
	fmt.Printf("response:%s \n", response.ToJsonString())
	fmt.Printf("结束更新记录:%d  \n \n", recordId)

}

//获取公网IP
func getIp(url string) string {
	client := http.Client{
		Timeout: 2 * time.Second,
	}
	resp, err := client.Get(url)
	if err != nil {
		fmt.Printf(" err:%s \n", err)
		return "error"
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	result := string(body)
	fmt.Printf("body:%s", string(body))
	fmt.Printf("StatusCode:%d \n", resp.StatusCode)
	if resp.StatusCode == 200 {
		fmt.Printf("ok" + " \n")
	}
	return result
}

//匹配是否是Ipv4
func matchIpv4(ip string) bool {
	matched, err := regexp.MatchString("((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}", ip)
	if err != nil {
		fmt.Println("ip匹配出现错误")
		return false
	}
	if matched { // 匹配上了
		if len(ip) < 16 {
			return true
		}
	}
	return false
}
  1. get缺少的go环境,进入dnspodRecord.go所在文件夹的命令框,完全执行后将会新增同名mod、sum文件
    1. 使用腾讯云镜像加速下载:
      1. Linux 或 MacOS:
        export GOPROXY=https://mirrors.tencent.com/go/
      2. Windows:
        set GOPROXY=https://mirrors.tencent.com/go/
    2. go mod初始化,将会生成一个同名mod文件
      go mod init dnspodRecord
    3. 拉取公共基础包
      go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common
    4. 拉取dnspod包
      go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod
    5. 本地电脑不可能只执行一次,拉取cron包
      go get github.com/robfig/cron
  2. 运行测试,将会30秒执行一次,将自己的IP地址同步到dnspod的记录解析中
    go run dnspodRecord.go

文章题目:go更新腾讯云DNSPod的解析记录
网站路径:http://cqcxhl.cn/article/dsoishi.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP