脚本功能:

  1. 遍历账号中管理的域名,并获取所有解析记录
  2. 将记录保存到excel文件中:域名为表名,一行一条记录
  3. 定期执行脚本,实现备份作用,并添加历史文件删除功能

脚本代码:

#!/bin/env python2.7
#coding:utf-8

import requests
import json
import datetime
import xlsxwriter
import os

TokenID = 22222
Token = '2222222222222333333333333'
token = "%d,%s"%(TokenID,Token)
loginData = { 
        "login_token":token,
        "format":"json",
    }   

def get_domains():

    r = requests.post(url="https://dnsapi.cn/Domain.List" , data=loginData)
    domains = r.json()['domains']
    print domains
    return domains

def get_records(domainid):

    loginData['domain_id'] = domainid
    r = requests.post(url="https://dnsapi.cn/Record.List" , data=loginData)
    records = r.json()['records']
    print records
    return records
		
 def rotate(days):
 
    Ftime = datetime.datetime.now() + datetime.timedelta(days=days)
    Ffile = 'dnspod_scan_' + Ftime.strftime("%Y-%m-%d") + '.xls'
    if os.path.exists(Ffile):
        os.remove(Ffile)

if __name__ =="__main__":

    date = datetime.datetime.now().strftime("%Y-%m-%d")
    workbook = xlsxwriter.Workbook('dnspod_scan_' + date + '.xls')

    fields = ['id','name','value','type','mx','ttl','line','weight','enabled','updated_on','remark']

    domains = get_domains()
    for item in domains:
        Dname = item['name']
        Did = item['id']
        worksheet = workbook.add_worksheet(Dname)
        bold = workbook.add_format({'bold': True})
        for field in range(0,len(fields)):
            worksheet.write(0,field,fields[field],bold)

        bold = workbook.add_format({'bold': False})
        records = get_records(Did)
        for record in range(0,len(records)):
            for key in range(0,len(fields)):
                if key == 1:
                    worksheet.write(record + 1,key,records[record][fields[key]] + '.' + Dname,bold)
                else:
                    worksheet.write(record + 1,key,records[record][fields[key]],bold)

    workbook.close()

    rotate(-10)