python 改变阿里云dns记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 改变阿里云dns记录相关的知识,希望对你有一定的参考价值。
# coding=utf-8
'''
Copyright 2016 imoobox.com
'''
import os
import sys
import click
import aliyun.api
MAX_TRY_COUNT = 3
def query_record_id(domain, sub_domain):
record_id = 0
q = aliyun.api.Dns20150109DescribeDomainRecordsRequest()
q.DomainName = domain
q.PageNumber = 1
q.PageSize = 20
q.RRKeyWord = sub_domain
q.TypeKeyWord = 'TXT'
res = q.getResponse()
count = res['TotalCount']
if count > 0:
print('Query %s sub domain is exists.' % sub_domain)
record_id = res['DomainRecords']['Record'][0]['RecordId']
return record_id
def add_sub_record(domain, sub_domain, value):
'''
http://dns.aliyuncs.com/?Action=AddDomainRecord
&DomainName=example.com
&RR=www
&Type=A
&Value=202.106.0.20
&TTL=600
&Line=default
&<公共请求参数>
'''
a = aliyun.api.Dns20150109AddDomainRecordRequest()
a.DomainName = domain
a.RR = sub_domain
a.Type = 'TXT'
a.Value = value
a.TTL = 600
a.Line = 'default'
for i in xrange(MAX_TRY_COUNT):
success = True
try:
res = a.getResponse()
except Exception as e:
success = False
print(e)
print("try %d time!" % (i))
if success:
break
if res.get('Code') is None:
print("DNS record has created.")
else:
print(res)
sys.exit(1)
def update_sub_record(domain, sub_domain, value, record_id):
m = aliyun.api.Dns20150109UpdateDomainRecordRequest()
m.Line = 'default'
m.TTL = 600
m.Type = 'TXT'
m.RR = sub_domain
m.RecordId = record_id
m.Value = value
res = {}
for i in xrange(MAX_TRY_COUNT):
success = True
try:
res = m.getResponse()
except Exception as e:
success = False
print(e)
print("try %d time!" % (i))
if success:
break
if res.get('Code') is None:
print("DNS record has updated.")
else:
print(res)
sys.exit(1)
@click.command()
@click.option('--domain', default=None, help='domain name')
@click.option(
'--sub_domain',
default='_acme-challenge',
help='sub domain for verify')
@click.option('--value', default=None, help='TXT record value')
@click.option('--key', default=None, help="aliyun accessKeyId")
@click.option('--secret', default=None, help="aliyun accessKeySecret")
def main(domain, sub_domain, value, key, secret):
if domain is None:
print('''Domain name is required''')
sys.exit(1)
if value is None:
print('''TXT record value is required''')
sys.exit(1)
key = os.getenv('ALIYUN_ACCESSKEYID') if key is None else key
if key is None:
print('''aliyun accessKeyId is required''')
sys.exit(1)
secret = os.getenv('ALIYUN_ACCESSKEYSECRET') if secret is None else secret
if secret is None:
print('''aliyun accessKeySecret is required''')
sys.exit(1)
aliyun.setDefaultAppInfo(key, secret)
record_id = query_record_id(domain, sub_domain)
if record_id == 0:
add_sub_record(domain, sub_domain, value)
else:
update_sub_record(domain, sub_domain, value, record_id)
if __name__ == '__main__':
main()
以上是关于python 改变阿里云dns记录的主要内容,如果未能解决你的问题,请参考以下文章