def setUpClass(cls):
        cls.dns = DNSimple(sandbox=True)
        domains = cls.dns.domains()

        for domain in domains:
            cls.dns.delete(domain['domain']['name'])

        new_domain = cls.dns.add_domain('test.test')
        cls.success_domain_id = new_domain['domain']['id']
        cls.success_domain_name = new_domain['domain']['name']

        new_record_data = {
            'record_type': 'CNAME',
            'name': 'test',
            'content': 'test.test'
        }
        new_record = cls.dns.add_record(new_domain['domain']['id'],
                                        new_record_data)
        cls.success_record_id = new_record['record']['id']
        cls.success_record_name = new_record['record']['name']

        record_to_delete_data = {
            'record_type': 'CNAME',
            'name': 'deletebyid',
            'content': 'test.test'
        }

        record_to_delete = cls.dns.add_record(cls.success_domain_id,
                                              record_to_delete_data)
        cls.record_to_delete_id = record_to_delete['record']['id']

        cls.failure_id = '0'
        cls.failure_name = 'i.dont.own.this.domain'
Example #2
0
    def __init__(self, context, domain='telephone.org'):
        self.context = context
        self.domain = domain
        creds = self.context.secrets['dns.dnsimple']

        self.api = DNSimple(
            username=creds['email'],
            password=creds['password']
        )
Example #3
0
def delete_record(data):
    dns = DNSimple(api_token=data['dnsimple_token'],
                   account_id=data['dnsimple_account'])
    if 'absent' in data['state']:
        for n in dns.records(data['domain']):
            if data['name'] == n['record']['name']:
                dns.delete_record(data['domain'], n['record']['id'])
                return (True, None, 'record deleted')
    return (False, None, 'no record deleted')
Example #4
0
def main():
    dns = DNSimple(username=USERNAME, password=PASSWORD)

    for net in NETWORKS:
        network = IPNetwork(net)
        for ip in network[1:-1]:
            print 'Adding mta{}-{}.{} IN A {}'.format(STARTFROM, ip.words[3], DOMAIN, str(ip))
            dns.add_record(DOMAIN, {'record_type': 'A', 'name': 'mta{}-{}'.format(STARTFROM, ip.words[3]),
                'content': str(ip)})
        STARTFROM += 1
Example #5
0
def del_record(request, rec_id):
    messages.get_messages(request)
    try:
        dns = DNSimple(username=settings.DNSIMPLE_USERNAME,
                       password=settings.DNSIMPLE_PASSWORD)
        dns.delete_record('raspi.tw', rec_id)
        messages.add_message(request, messages.SUCCESS, "成功删除记录!")
    except:
        messages.add_message(request, messages.WARNING, "记录删除失败!")
        pass
    return redirect('/dnsmanager')
Example #6
0
    def test_basic_authentication_from_credentials_file_raises_no_exception(
            self, credentials_file):
        # Create local credentials file
        file = open(credentials_file, 'w')
        file.writelines([
            "[DNSimple]\n", "email: {0}\n".format(os.getenv('DNSIMPLE_EMAIL')),
            "api_token: {0}\n".format(os.getenv('DNSIMPLE_API_TOKEN'))
        ])
        file.close()

        client = DNSimple(sandbox=True)

        client.domains()
Example #7
0
def subdomain_in_dnsimple(subdomain):
    dns = DNSimple(username=settings.DNSIMPLE_USERNAME,
                   password=settings.DNSIMPLE_PASSWORD)
    try:
        raspi_records = dns.records('raspi.tw')
    except:
        return None
    raspi_dns_records = list()
    for raspi_record in raspi_records:
        if raspi_record['record']['name'] == subdomain:
            t = dict()
            t['id'] = raspi_record['record']['id']
            t['name'] = raspi_record['record']['name']
            t['record_type'] = raspi_record['record']['record_type']
            t['content'] = raspi_record['record']['content']
            raspi_dns_records.append(t)
    return raspi_dns_records
Example #8
0
def add_record(request, subdomain):
    messages.get_messages(request)
    if request.method == 'POST':
        content = request.POST.get('content')
        record_type = request.POST.get('record_type')
        try:
            dns = DNSimple(username=settings.DNSIMPLE_USERNAME,
                           password=settings.DNSIMPLE_PASSWORD)
            dns.add_record('raspi.tw', {
                'name': subdomain,
                'record_type': record_type,
                'content': content
            })
            messages.add_message(request, messages.SUCCESS, "添加记录成功!")
        except:
            messages.add_message(request, messages.WARNING, "添加记录失败!")
            pass
    return redirect('/dnsmanager')
def dnsimple_set_ip(api_token, list_records, domain, subdomain, **kwargs):
    dns = DNSimple(api_token=api_token)

    records = [x['record'] for x in dns.records(domain)]
    if list_records:
        print_records(records)
        return

    subdomain_record = None
    for rec in records:
        if subdomain == rec['name']:
            subdomain_record = rec
            break

    if subdomain_record is None:
        create_subdomain(dns, domain, subdomain)
    else:
        update_subdomain(dns, domain, subdomain_record)
Example #10
0
    def test_domain_token_auth(self, client):
        domain_name = 'dnsimple-domain-token.test'

        domain = client.add_domain(domain_name)
        assert domain

        token_client = DNSimple(domain_token=domain['domain']['token'],
                                sandbox=True)

        with pytest.raises(DNSimpleException) as exception:
            token_client.domains()

        assert 'Authentication failed' in str(exception.value)
        assert token_client.domain(
            domain_name)['domain']['name'] == domain_name

        client.delete(domain_name)

        assert len(client.domains()) == 0
    def setUpClass(cls):
        cls.dns = DNSimple(sandbox=True)
        domains = cls.dns.domains()

        for domain in domains:
            cls.dns.delete(domain['domain']['name'])

        new_domain = cls.dns.add_domain('test.test')
        cls.success_domain_id = new_domain['domain']['id']
        cls.success_domain_name = new_domain['domain']['name']

        domain_to_delete_by_id = cls.dns.add_domain('deletebyid.test')
        cls.domain_to_delete_id = domain_to_delete_by_id['domain']['id']

        domain_to_delete_by_name = cls.dns.add_domain('deletebyname.test')
        cls.domain_to_delete_name = domain_to_delete_by_name['domain']['name']

        cls.failure_id = '0'
        cls.failure_name = 'i.dont.own.this.domain'
Example #12
0
def del_subdomain(request, subdomain):
    messages.get_messages(request)
    try:
        target = models.Subdomain.objects.get(user=request.user,
                                              name=subdomain)
        target.delete()
        dns = DNSimple(username=settings.DNSIMPLE_USERNAME,
                       password=settings.DNSIMPLE_PASSWORD)
        records_in_dnsimple = subdomain_in_dnsimple(subdomain)
        for rec in records_in_dnsimple:
            try:
                dns.delete_record('raspi.tw', rec['id'])
            except:
                messages.add_message(request, messages.WARNING,
                                     "和DNSimple联机有异常!")
                pass
        messages.add_message(request, messages.SUCCESS, "成功删除所有的记录!")
    except:
        messages.add_message(request, messages.WARNING, "记录删除失败!")
        pass
    return redirect('/dnsmanager')
Example #13
0
def create_record(data):
    nonexistant = False
    record = {
        'type': data['type'],
        'name': data['name'],
        'content': data['content'],
        'ttl': data['ttl']
    }

    dns = DNSimple(api_token=data['dnsimple_token'],
                   account_id=data['dnsimple_account'])
    if 'present' in data['state']:
        for n in dns.records(data['domain']):
            if record['name'] == n['record']['name']:
                res = dns.update_record(data['domain'], n['record']['id'],
                                        record)
                nonexistant = False
                return (True, res['record']['id'], 'record updated')
            else:
                nonexistant = True
        if nonexistant:
            res = dns.add_record(data['domain'], record)
            return (True, res['record']['id'], 'record added')
    return (False, "{}", 'no record added')
Example #14
0
uid = userinfo.pw_uid

#check if the desired site exists on this box
if not os.path.exists(site_root):
    os.makedirs(site_root)
    os.chmod(site_root, 0770)
    os.chown(site_root, uid, gid)

    os.makedirs(public_html)
    os.chmod(public_html, 0774)
    os.chown(public_html, uid, gid)

    #write the virtual host configuration file
    outfile = open(conf_file, 'w')

    outfile.write("<VirtualHost *:80>\n")
    outfile.write("\tServerName " + fqdn + "\n")
    outfile.write("\tDocumentRoot " + public_html + "\n")
    outfile.write("\tErrorLog /var/log/httpd/" + fqdn + ".log\n")
    outfile.write("\tCustomLog /var/log/httpd/" + fqdn + ".log combined\n")
    outfile.write("</VirtualHost>")

    outfile.close()

    #create DNSimple object
    dns = DNSimple(email=dnsimple_email_address, api_token=dnsimple_api_token)
    #create a dictionary with record data
    new_record = {'record_type': 'A', 'name': prefix, 'content': ip}
    #add the record
    dns.add_record(base, new_record)
Example #15
0
 def __init__(self):
     super().__init__(__file__)
     self.type = "cleaner"
     self.taskLog = []
     self.tmpSnapshotID = ""
     self.targetVPS = None
     self.queryInterval = int(self.config.get('cleaner', 'queryInterval'))
     self.createMinTime = int(self.config.get('cleaner', 'createMinTime'))
     self.destroyWaitTime = int(
         self.config.get('cleaner', 'destroyWaitTime'))
     self.timeZone = int(self.config.get('cleaner', 'timeZone'))
     self.sshPassword = self.config.get('cleaner', 'sshPassword')
     self.oldVPSList = []
     self.oldIPv4List = []
     self.vultrDestroyCoolTime = int(
         self.config.get('cleaner', 'vultrDestroyCoolTime'))
     self.destroyPool = ThreadPool(processes=self.maxThreads * 4)
     self.destroyResults = []
     self.VULTR512MPLANID = '200'
     self.VULTR1024MPLANID = '201'
     self.CONOHA1024PLANID = '7eea7469-0d85-4f82-8050-6ae742394681'
     self.lastException = None
     self.taskState = [
         'Pending', 'Destroying', 'Creating', 'Watching', 'Shiny☆',
         'Failing', 'Snapshotting', 'Destroying', 'Updating DNS',
         'Updating node info', 'Desnapshotting'
     ]
     self.taskStateID = 0
     self.birthTime = int(time.time())
     self.attempts = 0
     self.taskStateEmoji = {
         'working': '🔶',
         'success': '🔵',
         'fail': '🔴'
     }
     # Init Vultr api instance
     self.vultrApikey = self.config.get('cleaner', 'vultrApikey')
     self.vultr = Vultr(self.vultrApikey)
     # Init ConohaConfig instance
     self.conoha_conf = ConohaConfig(
         fromDict={
             'api': {
                 'user': self.config.get('cleaner', 'conohaUser'),
                 'passwd': self.config.get('cleaner', 'conohaPasswd'),
                 'tenant': self.config.get('cleaner', 'conohaTenant')
             }
         })
     self.conoha_token = None
     self.conoha_vmlist = None
     # Init dnsimple api instance
     self.dnsimpleUsername = self.config.get('cleaner', 'dnsimpleUsername')
     self.dnsimplePassword = self.config.get('cleaner', 'dnsimplePassword')
     self.dns = DNSimple(email=self.dnsimpleUsername,
                         password=self.dnsimplePassword)
     # Function dic for different VPS providers
     self.supportedVPSProviderList = ['Vultr', 'Conoha']
     self.supportedDNSProviderList = ['DNSimple']
     self.init_provider_api = {
         'Vultr': self.init_provider_api_vultr,
         'Conoha': self.init_provider_api_conoha
     }
     self.create_tmp_snapshot = {
         'Vultr': self.create_tmp_snapshot_vultr,
         'Conoha': self.create_tmp_snapshot_conoha
     }
     self.destroy_tmp_snapshot = {
         'Vultr': self.destroy_tmp_snapshot_vultr,
         'Conoha': self.destroy_tmp_snapshot_conoha
     }
     self.get_server_info = {
         'Vultr': self.get_server_info_vultr,
         'Conoha': self.get_server_info_conoha
     }
     self.destroy_and_create = {
         'Vultr': self.destroy_and_create_vultr,
         'Conoha': self.destroy_and_create_conoha
     }
     self.get_server_ip = {
         'Vultr': self.get_server_ip_vultr,
         'Conoha': self.get_server_ip_conoha
     }
     self.update_dns = {'DNSimple': self.update_dns_dnsimple}
Example #16
0
    def test_user_token_auth_raises_no_exception(self):
        client = DNSimple(email=os.getenv('DNSIMPLE_EMAIL'),
                          api_token=os.getenv('DNSIMPLE_API_TOKEN'),
                          sandbox=True)

        client.domains()
Example #17
0
    def test_authentication_with_invalid_credentials_raises(self):
        with pytest.raises(DNSimpleException) as exception:
            client = DNSimple(username='******', password='******')
            client.domains()

        assert 'Authentication failed' in str(exception.value)
Example #18
0
def client():
    return DNSimple(api_token=os.getenv('DNSIMPLE_API_TOKEN'), sandbox=True)
Example #19
0
    '''
    global shelf
    shelf[last_ip_key] = ip
    shelf.close()


if __name__ == '__main__':
    # Retrieve current IP address
    current_ip = get_current_ip_address()
    previous_ip = unshelve_previous_ip_address(
    )  # retrieve last known IP address

    # handle IP change.
    if current_ip == previous_ip:
        raise Exception("IP did not change since last update.")
    else:
        shelve_current_ip_address(current_ip)  # store current IP address

    # Fetch domain records using DNSimple API
    dns = DNSimple()
    records = dns.records(target_domain_name)
    target_record = find_record(records, target_record_name)
    new_record_data = {
        'content': current_ip
    }  # could also contain time to live, etc.

    print "Updating dom %s, rec %s with content: %s" % (
        target_record['domain_id'], target_record['id'], current_ip)
    dns.update_record(target_record['domain_id'], target_record['id'],
                      new_record_data)
Example #20
0
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import login, authenticate, logout
from .forms import LoginForm
from dnsimple import DNSimple
# Create your views here.

token = "tgOrJJxqkGfu3m01Mv0ssUo4S0MCpmkc"
email = "*****@*****.**"
password = "******"
dns = DNSimple(email, password)


def index(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid:
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
                return render(request, "main/index.html")
            else:
                return HttpResponse('veillez activer votre compte')
        else:
            return HttpResponse(
                "Vous n'avez pas de compte veillez vous inscrire")
    else:
        if request.user.is_authenticated():
            return HttpResponse("Vous avez un compte")
Example #21
0
 def dnsimple_client(self):
     """creates a dnsimple client object"""
     if self.account_email and self.account_api_token:
         self.client = DNSimple(sandbox=self.sandbox, email=self.account_email, api_token=self.account_api_token)
     else:
         self.client = DNSimple(sandbox=self.sandbox)
Example #22
0
 def __init__(self, account_id, api_token):
     self.dnsimple_client = DNSimple(api_token=api_token, account_id=account_id)
Example #23
0
    def test_authentication_with_no_credentials_raises(self):
        with pytest.raises(DNSimpleException) as exception:
            client = DNSimple()

        assert 'No authentication details provided.' in str(exception.value)
Example #24
0
 def test_config_auth(self):
     dns = DNSimple(sandbox=True)
     self.assertTrue(type(dns.domains()) is list)
Example #25
0
    def test_basic_authentication_raises_no_exceptions(self):
        client = DNSimple(username=os.getenv('DNSIMPLE_EMAIL'),
                          password=os.getenv('DNSIMPLE_PASSWORD'),
                          sandbox=True)

        client.domains()
Example #26
0
 def test_username_and_password_auth(self):
     dns = DNSimple(username='******',
                    password='******',
                    sandbox=True)
     self.assertTrue(type(dns.domains()) is list)
Example #27
0
 def test_email_and_api_token_auth(self):
     dns = DNSimple(email='*****@*****.**',
                    api_token='L0lkPizHnqVrsIyViLpB',
                    sandbox=True)
     self.assertTrue(type(dns.domains()) is list)
Example #28
0
def token_client(domain):
    return DNSimple(domain_token = domain['domain']['token'], sandbox = True)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            account_email=dict(required=False),
            account_api_token=dict(required=False, no_log=True),
            domain=dict(required=False),
            record=dict(required=False),
            record_ids=dict(required=False, type='list'),
            type=dict(required=False,
                      choices=[
                          'A', 'ALIAS', 'CNAME', 'MX', 'SPF', 'URL', 'TXT',
                          'NS', 'SRV', 'NAPTR', 'PTR', 'AAAA', 'SSHFP',
                          'HINFO', 'POOL'
                      ]),
            ttl=dict(required=False, default=3600, type='int'),
            value=dict(required=False),
            priority=dict(required=False, type='int'),
            state=dict(required=False, choices=['present', 'absent']),
            solo=dict(required=False, type='bool'),
        ),
        required_together=(['record', 'value']),
        supports_check_mode=True,
    )

    if not HAS_DNSIMPLE:
        module.fail_json(msg="dnsimple required for this module")

    account_email = module.params.get('account_email')
    account_api_token = module.params.get('account_api_token')
    domain = module.params.get('domain')
    record = module.params.get('record')
    record_ids = module.params.get('record_ids')
    record_type = module.params.get('type')
    ttl = module.params.get('ttl')
    value = module.params.get('value')
    priority = module.params.get('priority')
    state = module.params.get('state')
    is_solo = module.params.get('solo')

    if account_email and account_api_token:
        client = DNSimple(email=account_email, api_token=account_api_token)
    elif os.environ.get('DNSIMPLE_EMAIL') and os.environ.get(
            'DNSIMPLE_API_TOKEN'):
        client = DNSimple(email=os.environ.get('DNSIMPLE_EMAIL'),
                          api_token=os.environ.get('DNSIMPLE_API_TOKEN'))
    else:
        client = DNSimple()

    try:
        # Let's figure out what operation we want to do

        # No domain, return a list
        if not domain:
            domains = client.domains()
            module.exit_json(changed=False,
                             result=[d['domain'] for d in domains])

        # Domain & No record
        if domain and record is None and not record_ids:
            domains = [d['domain'] for d in client.domains()]
            if domain.isdigit():
                dr = next((d for d in domains if d['id'] == int(domain)), None)
            else:
                dr = next((d for d in domains if d['name'] == domain), None)
            if state == 'present':
                if dr:
                    module.exit_json(changed=False, result=dr)
                else:
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(
                            changed=True,
                            result=client.add_domain(domain)['domain'])
            elif state == 'absent':
                if dr:
                    if not module.check_mode:
                        client.delete(domain)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

        # need the not none check since record could be an empty string
        if domain and record is not None:
            records = [r['record'] for r in client.records(str(domain))]

            if not record_type:
                module.fail_json(msg="Missing the record type")

            if not value:
                module.fail_json(msg="Missing the record value")

            rr = next(
                (r for r in records
                 if r['name'] == record and r['record_type'] == record_type
                 and r['content'] == value), None)

            if state == 'present':
                changed = False
                if is_solo:
                    # delete any records that have the same name and record type
                    same_type = [
                        r['id'] for r in records if r['name'] == record
                        and r['record_type'] == record_type
                    ]
                    if rr:
                        same_type = [
                            rid for rid in same_type if rid != rr['id']
                        ]
                    if same_type:
                        if not module.check_mode:
                            for rid in same_type:
                                client.delete_record(str(domain), rid)
                        changed = True
                if rr:
                    # check if we need to update
                    if rr['ttl'] != ttl or rr['prio'] != priority:
                        data = {}
                        if ttl:
                            data['ttl'] = ttl
                        if priority:
                            data['prio'] = priority
                        if module.check_mode:
                            module.exit_json(changed=True)
                        else:
                            module.exit_json(changed=True,
                                             result=client.update_record(
                                                 str(domain), str(rr['id']),
                                                 data)['record'])
                    else:
                        module.exit_json(changed=changed, result=rr)
                else:
                    # create it
                    data = {
                        'name': record,
                        'record_type': record_type,
                        'content': value,
                    }
                    if ttl:
                        data['ttl'] = ttl
                    if priority:
                        data['prio'] = priority
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(changed=True,
                                         result=client.add_record(
                                             str(domain), data)['record'])
            elif state == 'absent':
                if rr:
                    if not module.check_mode:
                        client.delete_record(str(domain), rr['id'])
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

        # Make sure these record_ids either all exist or none
        if domain and record_ids:
            current_records = [
                str(r['record']['id']) for r in client.records(str(domain))
            ]
            wanted_records = [str(r) for r in record_ids]
            if state == 'present':
                difference = list(set(wanted_records) - set(current_records))
                if difference:
                    module.fail_json(msg="Missing the following records: %s" %
                                     difference)
                else:
                    module.exit_json(changed=False)
            elif state == 'absent':
                difference = list(set(wanted_records) & set(current_records))
                if difference:
                    if not module.check_mode:
                        for rid in difference:
                            client.delete_record(str(domain), rid)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

    except DNSimpleException as e:
        module.fail_json(msg="Unable to contact DNSimple: %s" % e.message)

    module.fail_json(msg="Unknown what you wanted me to do")
Example #30
0
 def test_domain_token_auth(self):
     # FIXME: Needs proper/publishable credentials/domain to work on sandbox
     dns = DNSimple(domain_token='DOMAIN_TOKEN', sandbox=True)
     with self.assertRaises(DNSimpleException):
         self.assertTrue(type(dns.domains()) is list)
     self.assertTrue(type(dns.records('DOMAIN')) is list)