linux下动态域名解析

有时候我们想把一台主机作为服务器,但是这台主机的IP是变动的,

这时候我们就需要进行动态域名解析。

首先我们需要到这里注册一个账号,然后是执行下面这个python脚本ddns.py

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import httplib, urllib
import socket
import time

params = dict(
    login_email="email", # replace with your email
    login_password="password", # replace with your password
    format="json",
    domain_id=100, # replace with your domain_od, can get it by API Domain.List
    record_id=100, # replace with your record_id, can get it by API Record.List
    sub_domain="www", # 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

def getip():
    sock = socket.create_connection(('ns1.dnspod.net', 6666))
    ip = sock.recv(16)
    sock.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, e:
            print e
            pass
        time.sleep(30)

这里需要将上面params里面的Email,密码,域名ID,记录ID等参数替换成你自己的,就可以运行了。 会在后台一直运行,每隔30秒检查一遍IP,如果修改了就更新IP。

以下是domain_id 和record_id的获取方法,只需要执行以下命令

获得domain_id可以用curl curl -k https://dnsapi.cn/Domain.List -d "login_email=xxx&login_password=xxx"

获得record_id类似 curl -k https://dnsapi.cn/Record.List -d "login_email=xxx&login_password=xxx&domain_id=xxx"

替换完成之后,执行该脚本即可,

为了防止重启主机是绑定的IP不变的情况,这里我们将该脚本加入开机自动执行里面即可

nohup python /home/ubuntu/ddns.py > /dev/null 2>&1 &
将该行加入/etc/rc.local里面


更多信息参考:https://gist.github.com/chuangbo/833369

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值