前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >dnspod通过接口解析本地ip python脚本

dnspod通过接口解析本地ip python脚本

作者头像
开心分享
发布2020-08-05 18:09:51
1.3K0
发布2020-08-05 18:09:51
举报

最近内网搭建了一台gitlab服务器,因为是内网没有公网ip,为了方便同事访问,dnspod直接解析了内网ip 但是网卡使用的是dhcp的获取ip的,每次关机可能会导致ip变动,所以通过dnspod接口改写了官方脚本来实现自动解析! 下面是我改下的脚本,你也可以把他写到计划任务里面多少分钟或小时执行一次!

代码语言:javascript
复制
#!/usr/bin/env python2
# -*- coding:utf-8 -*-

import httplib
import urllib
import socket
import time

# Use Token, check https://support.dnspod.cn/Kb/showarticle/tsid/227/
ID = "秘钥里面设置获取到"  # relace with yours, get it as link above show you.
Token = "秘钥里面设置获取到"  # relace with yours, get it as above link show you.
#

params = dict(
    login_token=("%s,%s" % (ID, Token)),
    format="json",
    domain_id=通过curl获取到,  # replace with your domain_od, can get it by API Domain.List
    # curl https://dnsapi.cn/Domain.List -d "login_token=你的id,Token&format=json"
    record_id=通过curl获取到,  # replace with your record_id, can get it by API Record.List
    #curl 'https://dnsapi.cn/Record.List' -d 'login_token=你的id,Token&format=json&domain_id=上面获取到的'
    sub_domain="dev",  # replace with your sub_domain
    record_line="默认",  #
)
current_ip = None


def ddns(ip):
    params.update(dict(value=ip))
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"}
    conn = httplib.HTTPSConnection("dnsapi.cn")
    conn.request("POST", "/Record.Ddns", urllib.urlencode(params), headers)

    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    print data
    conn.close()
    return response.status == 200

#获取本机ip
def getip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip


if __name__ == '__main__':
    while True:
        try:
            ip = getip()
            print ip
            if current_ip != ip:
                if ddns(ip):
                    current_ip = ip
        except Exception as e:
            print e
            pass
        time.sleep(30)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020年8月2日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档