• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

纯粹练手用的,大家轻喷

  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/v20210323"
)
//全局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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go语言学习小记 2020.10.30发布时间:2022-07-12
下一篇:
go-vscode-ubuntu20.04安装部署发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap