Ejemplo n.º 1
0
    def execute(self):
        if self.args['dns']:
            d_dns = sort.list_dns()
            if d_dns['status']:
                d_dns = d_dns['data']
                dat = list()
                for row in d_dns:
                    tmp = sort.get_data('zone',key=None,tags='nm_zone',value=row)['data'][0]
                    dat.append(tmp)
                d_unsync = list()
                d_id = list()
                for row in dat:
                    if row['state'] == 0:
                        d_unsync.append(row)
                        d_id.append(row['id_zone'])
                if d_unsync:
                    print("\n============================ Unsynchronized DNS ============================\n")
                    d_unsync = util.convert(d_unsync)
                    d_unsync = util.table_cleanup(d_unsync)
                    print(tabulate(d_unsync,headers='keys',showindex='always',tablefmt="rst"))
                    index = input("""
Type the index of the zone (0~{}), if you want to remove multiple record
separate the index using comma (,)
""".format(len(d_id)-1))
                    index = index.split(',')
                    index = util.check_availability(index,(len(d_id)-1))
                    for idx in index:
                        d_sync = { "sync" : "dns", "data" : {"id_zone" : d_id[int(idx)] } }
                        res=app.syncdat(d_sync)
                else :
                    print("All dns is already synchronized with knot server")            
        elif self.args['record']:
            zone = sort.list_dns()
            zone = zone['data']
            show = sort.list_record(zone)
            show = show['data']
            d_record = list()
            id_record = list()
            for row in show:
                if row['state'] == 0:
                    id_record.append(row['id_record'])
                    d_record.append(row)
            if len(d_record)<=0 :
                print("All record is already synchronized with Knot server")
                return 0
            else :
                d_record = util.table_cleanup(d_record)
                print(tabulate(d_record,headers="keys",showindex="always",tablefmt="rst"))
                index = input("""
    Type the index of the record (0~{}), if you want to remove multiple record
    separate the index using comma (,)
    """.format(len(d_record)-1))
                index = index.split(',')
                index = util.check_availability(index,(len(show)-1))
                for idx in index:
                    d_sync = {"sync" : "record", "data" : {"id_record" : id_record[int(idx)]}}
                    res=app.syncdat(d_sync)
                    if not res["status"]:
                        sys.stderr.write("Failure on index {}".format(idx))                 
Ejemplo n.º 2
0
    def execute(self):
        if self.args['ttl']:
            vallist = sort.listing_endpoint('ttl')
            print('Available TTL values are : ')
            print(vallist)
        elif self.args['type']:
            vallist = sort.listing_endpoint('type')
            print('Available Types are : ')
            print(vallist)
        elif self.args['dns']:
            vallist = sort.list_dns()
            if vallist['status'] == False:
                print(vallist['message'])
                exit()
            util.convert(vallist)
            vallist = vallist['data']
            d_dns = list()
            for row in vallist:
                state = sort.get_data("zone", "state", "nm_zone", row)
                state = state["data"][0]
                d_dns.append({"nm_zone": row, "state": state})
            print('Your Domains List Are : ')

            print(
                tabulate(d_dns,
                         headers='keys',
                         showindex='always',
                         tablefmt="rst"))
        elif self.args['record']:
            if self.args['--nm-zone']:
                zone = [self.args['--nm-zone']]
                tags = self.args
                vallist = ls.list_record(zone, tags)
            else:
                zone = sort.list_dns()
                try:
                    zone = zone['data']
                    vallist = sort.list_record(zone)
                except Exception:
                    sys.stderr.write(zone['message'] + '\n')
                    exit()
            if vallist['status'] and 'data' in vallist:
                vallist = util.table_cleanup(vallist['data'])
                print(
                    tabulate(vallist,
                             headers="keys",
                             showindex="always",
                             tablefmt="rst"))
            else:

                print("You have no record yet.")
Ejemplo n.º 3
0
    def execute(self):
        if self.args['dns']:
            zone = [self.args['--nm']]
            try :
                listdns = ls.list_record(zone)
                if 'data' in listdns:
                    listdns = listdns['data']
                    listdns = util.table_cleanup(listdns)
                    util.log_warning('The following record will also be deleted\n')
                    print(tabulate(listdns,headers="keys",tablefmt="rst"))
            except TypeError :
                print("DNS don't have record")
            if util.assurance() and check_password():
                delete.remove_zone(zone[0])
            else:
                exit()
        elif self.args['record']:
            if self.args['--nm-zone']:
                id_record = list()
                zone = [self.args['--nm-zone']]
                tags = self.args
                show = list()
                show = ls.list_record(zone,tags)
                try :
                    show = show['data']
                except Exception as e:
                    sys.stderr.write("Data doesn't exist")
                    sys.stderr.write(str(e))
                    exit()
            else:
                zone = ls.list_dns()
                zone = zone['data']
                show = ls.list_record(zone)
                show = show['data']
                show = util.convert(show)
                id_record = list()
            for row in show:
                row = util.convert(row)
                id_record.append(row['id_record'])
            if(len(show)>0):
                show = util.table_cleanup(show)
                print(tabulate(show, headers="keys" ,showindex="always",tablefmt="rst"))
                index = input("""
Type the index of the record (0~{}), if you want to remove multiple record
separate the index using comma (,)
""".format(len(show)-1))
                index = index.split(',')
                index = util.check_availability(index,(len(show)-1))
                sendid = list()
                for i in index:
                    sendid.append(id_record[int(i)])
                util.log_warning('Removing record is irreversible, are you sure ?\n')
                if util.assurance() and check_password():
                    res = delete.remove_record(sendid)
                else:
                    exit()                    
Ejemplo n.º 4
0
 def test_create_dns(self):
     new_zone = 'testclis.com'
     res = app.setDefaultDns(new_zone)
     dns = ls.list_dns()
     assert new_zone in dns['data']
Ejemplo n.º 5
0
 def test_list_dns(self):
     dnslist = ls.list_dns()
     dnslist = dnslist['data']
     assert 'testclis.com' in dnslist
Ejemplo n.º 6
0
    def execute(self):
        if self.args['dns']:

            check = util.check_existence('zone', self.args['--nm'])
            if check['status']:
                print("ZONE ALREADY EXIST")
            else:
                if 'expired' in check['message']:
                    print(check['message'])
                else:
                    app.setDefaultDns(self.args['--nm'])

        elif self.args['record']:
            if not self.args['--nm'] and not self.args["-f"]:
                dns = list_dns()
                if 'data' not in dns:
                    print("You don't have any dns!")
                else:
                    dns = dns['data']
                    util.convert(dns)
                    show = list()
                    for row in dns:
                        show.append({"DNS NAME": row})
                    print("Your Domain List are ")
                    print(
                        tabulate(show,
                                 headers='keys',
                                 showindex='always',
                                 tablefmt="rst"))
                    print("Pick a zone for your record!")
                    value = input("Zone Name : ")
                    while value not in dns:
                        print(
                            "You are not authorized to access {}, or it doesn't exist!"
                            .format(value))
                        value = input("Zone Name : ")
                    self.args['--nm-zn'] = value
                    value = input("Record name : ")
                    while not value:
                        print("Record name can't be empty string")
                        value = input("Record name : ")
                    self.args['--nm'] = value
                    print("Choose Record Type")
                    rectype = listing_endpoint('type')
                    rectype = rectype.replace('SOA\t', '')
                    rectype = rectype.replace('NS\t', '')
                    print(rectype)
                    rectype = rectype.split('\t')
                    del rectype[-1]
                    value = input("Record type : ")
                    while value.upper() not in rectype:
                        print("Type doesn't exist")
                        value = input("")
                    self.args['--type'] = value.upper()
                    ttl = listing_endpoint('ttl')
                    print("Available TTL values are :")
                    print(ttl)
                    ttl = ttl.split('\t')
                    del ttl[-1]
                    value = input("TTL : ")
                    while value not in ttl:
                        print("TTL value doesn't exist")
                        value = input("TTL : ")
                    self.args['--ttl'] = value
                    value = input("Content data : ")
                    while not value:
                        print("Content data can not be empty ")
                        value = input("Content data : ")
                    self.args['--nm-con'] = value
                    if self.args['--type'] == 'MX' or self.args[
                            '--type'] == 'SRV':
                        value = input("Content serial data : ")
                        while not value:
                            print("Content serial data can not be empty ")
                            value = input("Content serial data : ")
                        self.args['--nm-con-ser'] = value
                    print(
                        "You are about to create new record with following details :"
                    )
                    if self.args['--nm-con-ser']:
                        print(
                            """Record Name : {}       Zone : {}       Type : {}       TTL : {}
Content data : {}       Content serial data :{}""".format(
                                self.args['--nm'], self.args['--nm-zn'],
                                self.args['--type'], self.args['--ttl'],
                                self.args['--nm-con'],
                                self.args['--nm-con-ser']))
                    else:
                        print(
                            """Record Name : {}       Zone : {}       Type : {}       TTL : {}
Content data : {}      """.format(self.args['--nm'], self.args['--nm-zn'],
                                  self.args['--type'], self.args['--ttl'],
                                  self.args['--nm-con']))
                    affirm = input("Are you sure ? (Y)")
                    if affirm.upper() == 'Y':
                        self.args['--date'] = util.get_time()
                        app.setRecord(self.args)
                    else:
                        print("Cancelled")
                        exit()

            elif self.args['--nm'] and not self.args['-f']:
                check = dict()
                skip = False
                nodata = ' '
                temp = check_zone_authorization([self.args['--nm-zn']])
                check['zone'] = temp['status']
                temp = util.check_existence('type',
                                            self.args['--type'].upper())
                check['type'] = temp['status']
                temp = util.check_existence('ttl', self.args['--ttl'])
                check['ttl'] = temp['status']

                if self.args['--type'].upper(
                ) == 'MX' or self.args['--type'].upper() == 'SRV':
                    if self.args['--nm-con-ser'] is None:
                        util.log_warning(
                            "Record {} require serial content data".format(
                                self.args['--type'].upper()))
                        exit()
                for i in check:
                    if not check[i]:
                        nodata = nodata + i + ', '
                        skip = True

                if skip is True:
                    print(
                        "Value of " + nodata +
                        "doesn't exist. \nTry command ls to check available values"
                    )
                else:
                    self.args['--date'] = util.get_time()
                    app.setRecord(self.args)
            elif self.args['-f']:
                path = self.args['-f']
                pbar = tqdm(total=100)
                step = (100 / 3)
                pbar.set_description("Loading YAML")
                data = app.load_yaml(path)
                dnslist = list(data['data'].keys())
                check = check_zone_authorization(dnslist)
                sendlist = list()
                pbar.update(step)
                pbar.set_description("Parsing YAML")
                if 'data' not in check:
                    sendlist = dnslist
                    pbar.update(step)

                else:
                    for i in dnslist:
                        pbar.update(step / (len(dnslist)))
                        if i not in check['data']:
                            sendlist.append(i)
                pct = (100 / 3)
                if sendlist:
                    print(
                        str(sendlist) +
                        " doesn't exist. Do you want to create these dns and continue? (Y/N)"
                    )
                    if util.assurance():
                        for i in sendlist:
                            pbar.set_description("Creating DNS {}".format(i))
                            app.setDefaultDns(i)
                            pbar.update(pct / (3 * len(sendlist)))
                        pct = (100 / 4)
                    else:
                        print("ABORT")
                        exit()

                data = app.parse_yaml(data['data'])
                send = data['data']
                print(tabulate(send, headers="keys", tablefmt="rst"))
                print("Create records above ? (Y) ")
                if util.assurance():
                    pbar.set_description(" Creating Record")
                    for row in send:
                        pbar.set_description(desc="Creating " +
                                             row['--nm-zn'] + " " +
                                             row['--nm'] + " " + row['--type'])
                        pbar.update(pct / (len(send)))
                        res = app.setRecord(row)
                    pbar.close()
                    print('\n')
                else:
                    print("ABORT")
                    exit()