?大家注意:因為微信最近又改了推送機制,經(jīng)常有小伙伴說錯過了之前被刪的文章,比如前陣子冒著風(fēng)險寫的爬蟲,再比如一些限時福利,錯過了就是錯過了。
所以建議大家加個星標,就能第一時間收到推送。??

寫此篇文章,我花10塊購買了域名ssw.ski。
目的是編寫python腳本,通過dnspod api獲取個人域名內(nèi)的dns解析記錄,
免登錄實現(xiàn)域名的解析、修改和刪除:

為什么要編寫這個腳本?當你在公司負責(zé)很多的域名又經(jīng)常需要解析和查看,頻繁登錄網(wǎng)站去查去修改是一件費神的事。
上圖的賬號內(nèi)有2個域名ssw.fit和ssw.ski,我想給ssw.ski增加了一條A記錄,
把test子域名解析到我的linux云服務(wù)器,添加完后訪問test.ssw.ski

如何獲得域名解析信息
使用dnspod api, 說明見騰訊云文檔:https://docs.dnspod.cn/api/call-requency/
#獲取domain_id
curl 'https://dnsapi.cn/Domain.List' -d 'login_token=&format=json'
#獲取record_id
curl 'https://dnsapi.cn/Record.List' -d 'login_token=&format=json&domain_id='
獲取Token
訪問https://console.dnspod.cn/account/token/token ,創(chuàng)建一個秘鑰

完成后程序中可以使用ID,TOKEN來訪問api。
目標實現(xiàn)
一般都通過requests 的post方法訪問對應(yīng)網(wǎng)址。
不過這里用curl命令更簡介方便,它也可以發(fā)起post請求,并且一條命令解決。
所以用python來執(zhí)行l(wèi)inux下的curl命令就可以了:
class DomainHandler(object):
def __init__(self):
pass
def exec_cmd(self,cmd):
res = Popen(cmd, shell=True, stdout=PIPE)
ret = res.communicate()[0].decode('utf-8')
return ret.strip()
下面以添加A記錄為例。
添加字典對應(yīng)函數(shù)入口:
dic = {
'1':DomainHandler().add,
'2':DomainHandler().mod,
'3':DomainHandler().delete
}
tag = True
while tag:
print('''
1.增加
2.修改
3.刪除
q.退出
''')
choice = input('\033[1;42m輸入選項:\033[0m').strip()
if not choice:
continue
if choice == 'q':
break
if choice in dic:
dic[choice]()
else:
print('\033[31m選項不存在\033[0m')
添加記錄的入口函數(shù):
def add(self):
self.domain_info()
while tag:
self.domain_id = input('\033[1;42m輸入域名ID:\033[0m').strip()
if self.domain_id == 'q':
break
if not self.domain_id or not self.domain_id.isdigit():
print('\033[31merror id\033[0m')
continue
self.sub_domain = input('\033[1;42m子域名[@或*等]:\033[0m').strip()
self.record_type = input('\033[1;42m類型[A或CNAME]:\033[0m').strip()
self.address = input('\033[1;42m記錄值(ip或域名):\033[0m').strip()
if not self.sub_domain or not self.record_type or not self.address:
print('\033[31m參數(shù)不能為空\033[0m')
continue
self.add_Arecord(self.domain_id,self.sub_domain,self.record_type,self.address)
if self.domain_id == 'q' or self.record_type == 'q' or self.address == 'q':
self.tag = False
break
獲取域名信息:
def domain_info(self):
cmd = 'curl -s https://dnsapi.cn/Domain.List -d "login_token=391845,92f408bb5343e&format=json"'
data = json.loads(self.exec_cmd(cmd))
print(data)
for item in data['domains']:
print('%s:%s' % (item['name'], item['id']))
添加記錄:
def add_Arecord(self,domain_id,sub_domain,record_type,address):
print(domain_id,sub_domain,record_type,address)
cmd2 = "curl -s -X POST https://dnsapi.cn/Record.Create -d 'login_token=391845,92f408bb5343e&format=json&domain_id={0}&sub_domain={1}&record_type={2}&record_line_id=0&value={3}'".format(
domain_id, sub_domain, record_type, address)
r = json.loads(self.exec_cmd(cmd2))
print(r['status']['message'])
修改記錄
我想把test.ssw.ski的ip修改為1.1.1.1

ipconfig/flushdns刷新一下dns緩存,生效了:

文章還沒寫完,它就檢測到域名未備案了

不過前面的測試已經(jīng)ok,就不備案了。