利用Dnspod api批量更新添加DNS解析【python腳本】

需求:每天有大量的域名需要解析,變更,負責解析域名的妹子實屬傷不起,批量更新添加的需求誕生了。

參考文檔https://github.com/DNSPod/dnspod-python

         https://www.dnspod.cn/docs/index.html

注1依據個人笨拙的編程思想,碼了這麼一堆代碼,總算實現的添加更新功能,潛在bug尚不清楚。歡迎有興趣的朋友一起討論。

注2:以下代碼適用於python2.6以下,如果python2.6以上的需要將代碼中的:except Exception,e修改爲:except Exception as e

注3:在dnsapi.apicn源代碼中Ddns類中,需要把#record_type=record_type,這一行註釋掉進行安裝,已安裝的需要把pyc文件刪除,重新import即可


域名列表格式要求如下:

   域名                 電信IP,聯通IP

www.baidu.com            1.1.1.1,2.2.2.2

www.sohu.com             ,3.3.3.3

music.baidu.com          4.4.4.4,



代碼如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#who:[email protected]
#when:2013-08-14
import os,sys
from dnspod.apicn import *
domain_list=[]
domain_dic={}
illegal_list=[]
login_email="XXXXX"
password="XXXXX"
domain_file="/root/dns"
def domain_index(domain_file):
    all_domain_list=[]
    for line in file(domain_file).readlines():
        if line == '\n':
            continue
        if line[-1] == '\n':
            line=line[:-1]
            all_domain_list.append('.'.join(line.split()[0].split('.')[-2:]))
    domain_list=list(set(all_domain_list))
    api=DomainList(email=login_email,password=password)
    all_msg=api().get("domains")
    exists_list=[]
    for i in range(0,len(all_msg)):
        exists_list.append(all_msg[i].get("name"))
    for dom in domain_list:
        if dom not in exists_list:
            api_create=DomainCreate(dom,email=login_email,password=password)
            try:
                domain_create=api_create()
                all_msg=api().get("domains")
                for n in range(0,len(all_msg)):
                    if dom == all_msg[n].get("name"):
                        dom_id=all_msg[n].get("id")
                        domain_dic[dom]=dom_id
            except Exception,e:
                illegal_list.append(dom)
                #print "[Error:] %s" % e
                print """\033[31m[Error]: Create domain [ %s ] Fail
        .....You may not have permission to create it ! \033[0m""" % dom
        else:
            all_msg=api().get("domains")
            for n in range(0,len(all_msg)):
                if dom == all_msg[n].get("name"):
                    dom_id=all_msg[n].get("id")
                    domain_dic[dom]=dom_id
def add_record(domain,ip):
    if len(ip.split(',')) == 2:
        tel_ip=ip.split(',')[0]
        unic_ip=ip.split(',')[1]
    else:
        print "\033[31m[Error]: IP format error...\033[0m"
        #sys.exit()
    sub_dom='.'.join(domain.split('.')[:-2])
    dom_name=['.'.join(domain.split('.')[-2:])]
    for k,v in domain_dic.iteritems():
        if k in dom_name:
            domain_id=domain_dic[k]
    #print sub_dom   #debug
    api_subdom=RecordList(domain_id,email=login_email,password=password)
    try:
        rec_list=api_subdom().get("records")
        tmp_sub=[]
    try:
        rec_list=api_subdom().get("records")
        tmp_sub=[]
        for i in range(0,len(rec_list)):
            tmp_sub.append(rec_list[i].get("name"))
        if sub_dom in tmp_sub:
            #print "[Error]: Sub_domain [ %s.%s ] exists..." % (sub_dom,'.'.join(domain.split('.')[-2:]))
            update_record(rec_list,sub_dom,domain_id,'.'.join(domain.split('.')[-2:]),tel_ip,unic_ip)
        else:
            tel_record=RecordCreate(sub_dom,"A",u'默認'.encode("utf8"),tel_ip,600,domain_id=domain_id,email=login_email,password=password)
            unic_record=RecordCreate(sub_dom,"A",u'聯通'.encode("utf8"),unic_ip,600,domain_id=domain_id,email=login_email,password=password)
            tel_record()
            print "\033[32m[Notice]: Add record [ %s.%s ] -- [ %s ] successful!\033[0m" % (sub_dom,'.'.join(domain.split('.')[-2:]),tel_ip)
            unic_record()
            print "\033[32m[Notice]: Add record [ %s.%s ] -- [ %s ] successful!\033[0m" % (sub_dom,'.'.join(domain.split('.')[-2:]),unic_ip)
    except:
        print "\033[31m[Error]: Add sub_domain record some error...\033[0m"
        #sys.exit()
def update_record(rec_list,sub_dom,domain_id,dom,tel_ip="",unic_ip=""):
    for nu in range(0,len(rec_list)):
        if sub_dom == rec_list[nu].get("name"):
            record_id=rec_list[nu].get("id")
            if rec_list[nu].get("line") == u"默認" and tel_ip:
                try:
                    tel_update_record=RecordDdns(record_id,sub_dom,"默認",domain_id=domain_id,ttl=600,value=tel_ip,email=login_email,password=password)
                    tel_update_record()
                    print "\033[32m[Notice]: Update [ %s.%s ] --- [ %s ] Successful!\033[0m" % (sub_dom,dom,tel_ip)
                except Exception,e:
                    print "[Error]: %s" % e
                    print "\033[31m.......... Update [ %s.%s ] --- [ %s ] Fail!\033[0m" % (sub_dom,dom,tel_ip)
            elif rec_list[nu].get("line") == u"聯通" and unic_ip:
                try:
                    unic_update_record=RecordDdns(record_id,sub_dom,"聯通",domain_id=domain_id,ttl=600,value=unic_ip,email=login_email,password=password)
                    unic_update_record()
                    print "\033[32m[Notice]: Update [ %s.%s ] --- [ %s ] Successful!\033[0m" % (sub_dom,dom,unic_ip)
                except Exception,e:
                    print "[Error]: %s" % e
                    print "\033[31m.......... Update [ %s.%s ] --- [ %s ] Fail!\033[0m" % (sub_dom,dom,unic_ip)
                                                                                                                                                                                                            
if __name__ == '__main__':
    if os.path.isfile(domain_file):
        domain_index(domain_file)
        for line in file(domain_file).readlines():
            if line == '\n':
                continue
            if line[-1] == '\n':
                line=line[:-1]
                if illegal_list:
                    for g in illegal_list:
                        try:
                            line.split()[0].index(g)
                        except:
                            add_record(line.split()[0],line.split()[1])
                else:
                    add_record(line.split()[0],line.split()[1])
    else:
        print "\033[31m[Error]: Domain file [ %s ]not found...\033[0m" % domain_file
        sys.exit()






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章