Exemple #1
0
def update_domain(domain, new_ip, rrs):
    cli = client.AcsClient(KEY, SECRET, REGION)

    req = DescribeDomainRecordsRequest()
    req.set_DomainName(domain)
    req.set_accept_format('json')
    resp = cli.do_action(req)

    records = json.loads(resp)['DomainRecords']['Record']

    for rec in records:
        if rec['Type'] != 'A':
            continue

        if rec['RR'] not in rrs:
            continue
        
        if rec['Value'] == new_ip:
            print_('Not need refresh, same as now.', new_ip, rec['RR'])
            continue

        req = UpdateDomainRecordRequest()
        req.set_RecordId(rec['RecordId'])
        req.set_Value(new_ip)
        req.set_RR(rec['RR'])
        req.set_Type(rec['Type'])

        req.set_accept_format('json')
        
        resp = cli.do_action(req)
        result = json.loads(resp)
        if 'Code' in result:
            raise Exception(result['Message'])
Exemple #2
0
    def get_domain_records(self, domain_name, page_num=1, page_size=20):
        '''
        获取域名解析记录列表
        '''
        request = DescribeDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain_name)
        request.set_PageNumber(page_num)
        request.set_PageSize(page_size)

        data = self._request(request)
        total = data.get('TotalCount')
        data = data.get('DomainRecords')
        data_list = data.get('Record')
        data = {
            'total': total,
            'data_list': data_list,
        }
        return data
Exemple #3
0
 def query(self):
     '''Query all host records.'''
     req = DescribeDomainRecordsRequest()
     req.set_accept_format('json')
     req.set_DomainName(self.__domain)
     js = json.loads(self.__bs.do_action_with_exception(req).decode())
     ret = {}
     strs = ''
     for x in js['DomainRecords']['Record']:
         RR = x['RR']
         Type = x['Type']
         Value = x['Value']
         RecordId = x['RecordId']
         TTL = x['TTL']
         strs = strs + '[*]%8s.%s -> %-16s;  %-8s;%d\n' % (
             RR, self.__domain, Value, Type, TTL)
         ret[RR] = [Value, Type, TTL, RecordId]
     self.__print = strs
     return ret
Exemple #4
0
    def part_sub_domains(self):
        """
        查询所有子域名
        :return: list|None
        """
        try:
            client = AcsClient(self.key, self.secret, 'cn-hangzhou')
            request = DescribeDomainRecordsRequest()
            request.set_accept_format('json')
            request.set_PageSize(500)  # 分页查询时设置的每页行数,最大值500,默认为20
            request.set_DomainName(self.second_level_domain)
            response = client.do_action_with_exception(request)

            response = json.loads(response)
            records = response["DomainRecords"]["Record"]

            if not records:
                print(F"query sub domains failed: {response}")
                return None

            data = []
            for item in records:
                if item["RR"] != self.prefix_domain and item["Type"] not in ("MX", "TXT", "SRV", "NS") and \
                        item["RR"].endswith(self.prefix_domain):
                    data.append({
                        "name": item["RR"] + "." + item["DomainName"],
                        "type": item["Type"],
                        # "line": self.record_line(key=item["Line"]),
                        "value": item["Value"],
                        # "mx": item["Priority"] if "Priority" in item else "0",
                        # "ttl": item["TTL"],
                        # "status": "正常" if item["Status"] == "ENABLE" else "暂停",  # ENABLE DISABLE
                    })
            return data

        except KeyError as e:
            print(F"domain not exist: {e}")

        except Exception:
            print("query sub domains unknown exception")
            print(traceback.format_exc())
    def __get_total_page_num(self, domainName, PageNum=1, PageSize=1):
        '''
        获取解析记录页数
        :param domainName: 域名
        :return:
        '''
        request = DescribeDomainRecordsRequest()
        request.set_DomainName(domainName)
        request.set_PageNumber(PageNum)
        request.set_PageSize(PageSize)
        response = self.__do_action(request)
        if self.TotalPageNum != 0:
            return response['DomainRecords']['Record']

        else:
            if int(response['TotalCount']) % self.PageSize != 0:
                self.TotalPageNum = int(
                    response['TotalCount'] / self.PageSize) + 1
            else:
                self.TotalPageNum = int(response['TotalCount'] / self.PageSize)
            return self.TotalPageNum
    def get_domain_records(self,
                           domain_name: str,
                           host_record_keyword: str = None,
                           type_keyword: str = 'A',
                           value_keyword: str = None) -> dict:
        if not self._data_valid(domain_name):
            raise RuntimeError('缺少域名名称')

        request = DescribeDomainRecordsRequest()
        request.set_accept_format('json')

        request.set_DomainName(domain_name)
        # request.set_PageSize('100')
        if self._data_valid(host_record_keyword):
            request.set_RRKeyWord(host_record_keyword)
        request.set_TypeKeyWord(type_keyword)
        if self._data_valid(value_keyword):
            request.set_ValueKeyWord(value_keyword)

        response = self.client.do_action_with_exception(request)  # type: bytes
        response_data = json.loads(response.decode('utf-8'))
        return response_data
Exemple #7
0
def get_domain_record(client, domain, rr):
    """
    获取解析记录
    :param client
    :param domain:
    :param rr:
    :return:
    """
    request = DescribeDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(domain)
    request.set_KeyWord(rr)

    response = client.do_action_with_exception(request)
    records = json.loads(response)['DomainRecords']['Record']

    if len(records) > 0:
        for item in records:
            if item['RR'] == rr:
                return item

    return None
Exemple #8
0
def get_domain_record(keyID, keySecret, domainName, recordName):
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest

    client = AcsClient(keyID, keySecret, 'cn-hangzhou')

    request = DescribeDomainRecordsRequest()
    request.set_accept_format('json')

    request.set_DomainName(domainName)
    request.set_RRKeyWord(recordName)

    response = client.do_action_with_exception(request)

    records = json.loads(str(response,
                             encoding='utf-8'))["DomainRecords"]["Record"]
    records = filter(
        lambda record: record["RR"] == recordName and record["Type"] == "A",
        records)
    records = list(records)
    assert len(records) == 1, "找不到域名%s的A记录%s" % (domainName, recordName)

    return records[0]
Exemple #9
0
def get_domain_ip(domainname, rrkeyworld, _type):
    try:
        request = DescribeDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_TypeKeyWord(_type)
        request.set_DomainName(domainname)
        request.set_RRKeyWord(rrkeyworld)

        response = client.do_action_with_exception(request)
        try:
            source_data = str(response, encoding='utf-8')
            print('请求数据成功')
        except Exception as e:
            print('请求数据失败')
            print(e)
            sys.exit()
        try:
            datas = json.loads(source_data)['DomainRecords']['Record'][0]
            print('找到主机记录')
        except Exception:
            print('没有找到主机记录')
            sys.exit()

        if datas:
            print('\t域名\t: ' + str(datas['RR'] + '.' + datas['DomainName']))
            print('\t类型\t: ' + str(datas['Type']))
            print('\t记录值\t: ' + str(datas['Value']))
            print('\tTTL\t: ' + str(datas['TTL']))
            print('\tStatus\t: ' + str(datas['Status']))
            return str(datas['Value']), str(datas['RR']), str(
                datas['RecordId']), str(datas['Type'])
        else:
            print('请求数据失败')
            print(source_data)
    except Exception as e:
        print('请求数据失败')
        print(e)
Exemple #10
0
def get_record_by_domain(domain):
    request = DescribeDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(domain)
    return client.do_action_with_exception(request)
Exemple #11
0
class AliDNS():

    def __init__(self):
        with open(os.path.abspath('config.json'), 'r') as f:
            self.config = json.load(f)
            self.AccessKeyId = self.config['AccessKeyId']
            self.AccessKeySecret = self.config['AccessKeySecret']
            self.Region = self.config['Region']
            self.client = AcsClient(self.AccessKeyId, self.AccessKeySecret, self.Region)

    def Get_RecordId(self, DomainName, RR):
        ''' 获取域名的RecordId'''
        self.request = CommonRequest()
        self.request.set_domain('alidns.aliyuncs.com')
        self.request.set_version('2015-01-09')
        self.request.set_action_name('DescribeDomainRecords')
        self.request.add_query_param('DomainName', DomainName)
        try:
            response = self.client.do_action_with_exception(self.request)
            jsonObj = json.loads(response.decode("UTF-8"))
            records = jsonObj["DomainRecords"]["Record"]
            for code in records:
                if code["RR"] == RR:
                    return code["RecordId"]
        except:
            Logger().info("Error")

    def Add_Domain_Record(self, RR, value, DomainName, Type):
        '''新增域名解析方法:
            RR:二级域名记录值;
            value:所要解析的IP地址;
            DominName:主域名
        '''
        self.request.set_accept_format('json')
        self.request.set_domain('alidns.aliyuncs.com')
        self.request.set_method('POST')
        self.request.set_version('2015-01-09')
        self.request.set_action_name('AddDomainRecord')
        self.request.add_query_param('RR', RR)
        self.request.add_query_param('Type', Type)
        self.request.add_query_param('Value', value)
        self.request.add_query_param('DomainName', DomainName)
        response = self.client.do_action(self.request)
        jsonObj = json.loads(response.decode("UTF-8"))
        Logger().info(jsonObj)

    def update_Domain_Record(self, RR, value, Type, DomainName):
        '''修改域名解析记录'''
        self.request = CommonRequest()
        record_id = self.Get_RecordId(RR=RR, DomainName=DomainName)
        self.request.set_accept_format('json')
        self.request.set_domain('alidns.aliyuncs.com')
        self.request.set_method('POST')
        self.request.set_version('2015-01-09')
        self.request.set_action_name('UpdateDomainRecord')
        self.request.add_query_param('RR', RR)
        self.request.add_query_param('Type', Type)
        self.request.add_query_param('Value', value)
        self.request.add_query_param('RecordId', record_id)
        response = self.client.do_action(self.request)
        jsonObj = json.loads(response.decode("UTF-8"))
        Logger().info(jsonObj)

    def Get_Result(self, keyword, domain, Type):
        self.request = DescribeDomainRecordsRequest()
        self.request.set_accept_format('json')
        self.request.set_RRKeyWord(keyword)
        self.request.set_DomainName(domain)
        response = self.client.do_action_with_exception(self.request)
        jsonObj = json.loads(response.decode("UTF-8"))
        try:
            for i in jsonObj['DomainRecords']['Record']:
                if i['Type'] == Type and i['RR'] == keyword:
                    return i['Value']
        except:
            return '127.0.0.1'

    def run(self):
        while 1:
            value = GetIP().getLocalHost()
            for i in range(len(self.config['args'])):
                Type, domain = self.config['args'][i]['Type'], self.config['args'][i]['domain']
                for r in self.config['args'][i]['RR']:
                    domainIP = self.Get_Result(r, domain, Type)
                    if domainIP == value:
                        Logger().info('{}.{}:当前解析记录无异常'.format(r, domain))
                    elif domainIP == '127.0.0.1':
                        continue
                    else:
                        Logger().info('{}.{}:当前解析地址为:{}'.format(r, domain, domainIP))
                        Logger().info('{}.{}:域名当前解析地址与本地地址不致,开修改解析记录'.format(r, domain))
                        self.update_Domain_Record(RR=r, value=value, Type=Type, DomainName=domain)
            Logger().info('进程休眠中...')
            time.sleep(1800)
Exemple #12
0
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.DeleteDomainRecordRequest import DeleteDomainRecordRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest

domain = idna.decode(os.getenv("DOMAIN"))
accessKeyID = os.getenv("ACCESSKEYID")
accessSecret = os.getenv("ACCESSSECRET")
apinode = "cn-shanghai"

client = AcsClient(accessKeyID, accessSecret, apinode)

request = DescribeDomainRecordsRequest()
request.set_accept_format('json')

request.set_DomainName(domain)

response = client.do_action_with_exception(request)
records = json.loads(str(response, encoding='utf-8'))
records = records["DomainRecords"]["Record"]

for r in records:
    if r["Type"] == "TXT" and r["RR"] == "_acme-challenge":
        RecordId = r["RecordId"]

        request = DeleteDomainRecordRequest()
        request.set_accept_format('json')

        request.set_RecordId(RecordId)

        response = client.do_action_with_exception(request)
Exemple #13
0
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest

form = cgi.FieldStorage()

access_key_id = form.getvalue('access_key_id')
access_secret = form.getvalue('access_secret')
dns_domain_name = form.getvalue('dns_domain_name')
dns_rr = form.getvalue('dns_rr')
dns_type = form.getvalue('dns_type')
dns_value = form.getvalue('dns_value')

client = AcsClient(access_key_id, access_secret, 'cn-hangzhou')

request = DescribeDomainRecordsRequest()
request.set_accept_format('json')
request.set_DomainName(dns_domain_name)
request.set_RRKeyWord(dns_rr)
response = client.do_action_with_exception(request)

data2 = json.loads(str(response, encoding='utf-8'))

dns_record_id = data2['DomainRecords']["Record"][0]["RecordId"]
old_value = data2['DomainRecords']["Record"][0]["Value"]

if old_value != dns_value:

    request2 = UpdateDomainRecordRequest()
    request2.set_accept_format('json')
    request2.set_Value(dns_value)
    request2.set_Type(dns_type)
    request2.set_RR(dns_rr)