Beispiel #1
0
    def update_dns_godaddy(self, domain, record_type, record):
        from godaddypy import Client, Account
        from godaddypy.client import BadResponse

        def get_domains(client):
            a = set()
            for d in client.get_domains():
                time.sleep(0.25)
                a.add(d)
            return a

        key = self.genv.godaddy_api_keys[domain]['key']
        secret = self.genv.godaddy_api_keys[domain]['secret']
        my_acct = Account(api_key=key, api_secret=secret)
        client = Client(my_acct)
        #allowed_domains = set(client.get_domains())
        allowed_domains = get_domains(client)
        #         print('allowed_domains:', allowed_domains)
        assert domain in allowed_domains, \
            'Domain %s is invalid this account. Only domains %s are allowed.' % (domain, ', '.join(sorted(allowed_domains)))
        #client.add_record(domain, {'data':'1.2.3.4','name':'test','ttl':3600, 'type':'A'})
        print('Adding record:', domain, record_type, record)
        if not self.dryrun:
            try:
                max_retries = 10
                for retry in xrange(max_retries):
                    try:
                        client.add_record(
                            domain, {
                                'data': record.get('ip', record.get('alias')),
                                'name': record['name'],
                                'ttl': record['ttl'],
                                'type': record_type.upper()
                            })
                        print_success('Record added!')
                        break
                    except ValueError as exc:
                        print(
                            'Error adding DNS record on attempt %i of %i: %s' %
                            (retry + 1, max_retries, exc))
                        if retry + 1 == max_retries:
                            raise
                        else:
                            time.sleep(3)
            except BadResponse as e:
                if e._message['code'] == 'DUPLICATE_RECORD':
                    print('Ignoring duplicate record.')
                else:
                    raise
Beispiel #2
0
    def update_dns_godaddy(self, domain, record_type, record):
        from godaddypy import Client, Account
        from godaddypy.client import BadResponse

        def get_domains(client):
            a = set()
            for d in client.get_domains():
                time.sleep(0.25)
                a.add(d)
            return a

        key = self.genv.godaddy_api_keys[domain]['key']
        secret = self.genv.godaddy_api_keys[domain]['secret']
        my_acct = Account(api_key=key, api_secret=secret)
        client = Client(my_acct)
        #allowed_domains = set(client.get_domains())
        allowed_domains = get_domains(client)
#         print('allowed_domains:', allowed_domains)
        assert domain in allowed_domains, \
            'Domain %s is invalid this account. Only domains %s are allowed.' % (domain, ', '.join(sorted(allowed_domains)))
        #client.add_record(domain, {'data':'1.2.3.4','name':'test','ttl':3600, 'type':'A'})
        print('Adding record:', domain, record_type, record)
        if not self.dryrun:
            try:
                max_retries = 10
                for retry in six.moves.range(max_retries):
                    try:
                        client.add_record(
                            domain,
                            {
                                'data': record.get('ip', record.get('alias')),
                                'name': record['name'],
                                'ttl': record['ttl'],
                                'type': record_type.upper()
                            })
                        print_success('Record added!')
                        break
                    except ValueError as exc:
                        print('Error adding DNS record on attempt %i of %i: %s' % (retry+1, max_retries, exc))
                        if retry + 1 == max_retries:
                            raise
                        else:
                            time.sleep(3)
            except BadResponse as e:
                if e._message['code'] == 'DUPLICATE_RECORD':
                    print('Ignoring duplicate record.')
                else:
                    raise
Beispiel #3
0
def put_txt(domain, host):

    my_acct = Account(api_key=PUBLIC_KEY, api_secret=SECRET_KEY)
    client = Client(my_acct)

    #Search and delete any old records.
    res = self.client.get_records(domain, record_type='TXT', name=host)
    for entry in res:
        self.client.delete_records(self.domain, name=self.host)

    #domain: lnxsystems.com
    #host: www
    #data: what o point to
    client.add_record(domain, {
        'name': host,
        'ttl': int(self.ttl),
        'data': self.data,
        'type': 'TXT'
    })
Beispiel #4
0
class TestGodaddy(unittest2.TestCase):
    def setUp(self):
        self.client = Client(
            Account(api_key=os.environ['godaddy_key'],
                    api_secret=os.environ['godaddy_secret']))


# this needs fixing to read the record first, then re-add it

    @unittest2.skip("fixme and implement")
    def test_duplicate_records_fail(self):
        # with self.assertRaises (HTTPError):
        #with self.assertRaises (Exception):
        with self.assertRaises(BadResponse):
            self.client.add_record('iotaa.co.uk', {
                'data': '52.49.186.47',
                'name': 'jenkins',
                'ttl': 600,
                'type': 'A'
            })
for domain in domain_list:
  for a_record in a_record_list:
    print("Attemping update for: %s.%s" % (a_record, domain))
    try:
      records = userClient.get_records(domain, name=a_record, record_type='A')
      if len(records) == 0:
        print("No records returned for name.domain: %s.%s" % (a_record, domain))
        if create_missing_records:
          new_record =  {
                          "type": 'A',
                          "name": a_record,
                          "data": publicIP,
                          "ttl": 600,
                        }
          add_record_result = userClient.add_record(domain, new_record)
          if not add_record_result:
            print("ERROR - Unable to add missing A-record: %s.%s" % (a_record, domain))
          else:
            print("Successfully added missing A-Record: %s.%s" % (a_record, domain))
      for record in records:
        if publicIP != record["data"]:
          updateResult = userClient.update_record_ip(publicIP, domain, name=a_record, record_type='A')
          if updateResult is True:
            print('Update ended with no Exception. %s.%s now assigned IP %s'  %(a_record, domain, publicIP))
        else:
          print('No DNS update needed.')
    except:
      print(sys.exc_info()[1])
      sys.exit()
Beispiel #6
0
#!/usr/bin/python

import sys
import os

from godaddypy import Client, Account
my_acct = Account(api_key=os.environ['GODAD_key'],
                  api_secret=os.environ['GODAD_secret'])
client = Client(my_acct)

client.add_record(sys.argv[3], {
    'data': sys.argv[2],
    'name': sys.argv[1],
    'ttl': 3600,
    'type': 'A'
})
paramDNSNAME = 'dnsrecord name'  # for wildcard = _acme-challenge'

userAccount = Account(api_key=paramAPIKEY, api_secret=paramAPISECRET)
userClient = Client(userAccount)

domain = certDOMAIN
n_record = paramDNSNAME
v_record = certVALIDATION

try:
    records = userClient.get_records(domain, name=n_record, record_type='TXT')
    print(records)
    if len(records) == 0:
        userClient.add_record(domain, {
            'data': v_record,
            'name': n_record,
            'ttl': 600,
            'type': 'TXT'
        })
    records = userClient.get_records(domain, name=n_record, record_type='TXT')
    for record in records:
        if v_record != record["data"]:
            updateResult = userClient.update_record(domain, {
                'data': v_record,
                'name': n_record,
                'ttl': 600,
                'type': 'TXT'
            })
            if updateResult is True:
                print('Update ended with no Exception.')
                time.sleep(30)
            else:
                        domain,
                        name=record["name"],
                        record_type=record_type)
                    print('Registry updated.')

                if updateResult != True:
                    print('Error updating registry.')

        for subdomain in subdomains_tmp:

            print(subdomain)
            print('Creating subdomain')

            if userClient.add_record(
                    domain, {
                        'data': publicIP,
                        'name': subdomain,
                        'ttl': 3600,
                        'type': record_type
                    }):
                print('Subdomain created')
            else:
                print('Subdomain creation error')

    except:
        print(sys.exc_info()[1])

    lastIP = publicIP

    time.sleep(sleep_time)
class GoDaddy:
    def __init__(self, **config):
        self.domain_name = config.get('domain_name')
        self.alias_name = config.get('alias_name')
        self.__access_id = config.get('access_id')
        self.acct = Account(api_key=self.__access_id,
                            api_secret=config.get('access_key'))
        self.__client = Client(self.acct)

    def describe_record(self, *args, **kwargs):
        return self.__client.get_records(kwargs.get('domain_name'),
                                         record_type=kwargs.get('domain_type'),
                                         name=kwargs.get('domain_rr'))

    def add_record(self, *args, **kwargs):
        params = dict(name=kwargs.get('domain_rr'),
                      data=kwargs.get('domain_value'),
                      type=kwargs.get('domain_type'),
                      ttl=int(kwargs.get('domain_ttl')))

        result_data = self.__client.add_record(kwargs.get('domain_name'),
                                               params)
        if result_data is True:
            result_data = str(uuid())
        return result_data

    def update_record(self, *args, **kwargs):
        params = dict(name=kwargs.get('domain_rr'),
                      data=kwargs.get('domain_value'),
                      type=kwargs.get('domain_type'),
                      ttl=int(kwargs.get('domain_ttl')))
        result_data = self.__client.update_record(kwargs.get('domain_name'),
                                                  params)
        return result_data

    def remark(self, *args, **kwargs):
        return dict(code=0, msg='GoDaddy不支持修改')

    def set_record_status(self, *args, **kwargs):
        if kwargs.get('status') in ['开启', '启用', 'Enable', 'enable', 'ENABLE']:
            self.add_record(**kwargs)
        elif kwargs.get('status') in ['暂停', '禁用', 'disable']:
            self.del_record(**kwargs)
        else:
            return False
        return True

    def del_record(self, *args, **kwargs):
        domain_name = kwargs.get('domain_name')
        name = kwargs.get('domain_rr')
        record_type = kwargs.get('domain_type')
        result_data = self.__client.delete_records(domain_name,
                                                   name,
                                                   record_type=record_type)
        return result_data

    def describe_domains(self):
        domain_list = self.__client.get_domains()
        if not domain_list: return False
        for domain in domain_list:
            domain_info_list = self.__client.get_domain_info(domain)
            domain_info_list['records'] = len(
                self.__client.get_records(domain))
            yield domain_info_list

    def record_generator(self, **domain):
        record_info_list = self.__client.get_records(domain.get('domain'))
        if not record_info_list: return False
        for record in record_info_list:
            yield dict(domain_name=domain.get('domain'), data_dict=record)
def domainTail(domain):
    domain = domain.split(".")
    domain = domain[:len(domain)-2]
    tmp = []
    for level in domain:
        if "*" not in level:
            tmp.append(level)
    domain = '.'.join(tmp)
    if domain:
        return domain
    return False
    
try:
    if len(CERTBOT_DOMAIN.split(".")) > 2:
        domain_tail = domainTail(CERTBOT_DOMAIN)
        client.add_record(CERTBOT_DOMAIN, {'data':CERTBOT_VALIDATION,'name':f'_acme-challenge.{domain_tail}','ttl':TTL,'type':'TXT'})
    else:
        client.add_record(CERTBOT_DOMAIN, {'data':CERTBOT_VALIDATION,'name':'_acme-challenge','ttl':TTL, 'type':'TXT'})
except Exception as err:
    logging.error(f"client.add_record error: {err}")
    if "UNABLE_TO_AUTHENTICATE" in err:
        sys.exit(1)

def mainDomainTail(domain):
    domain = domain.split(".")
    domain = domain[len(domain)-2:]
    tmp = []
    for level in domain:
        if "*" not in level:
            tmp.append(level)
    domain = '.'.join(tmp)
Beispiel #11
0
	with open("/var/nomx/localCidr", "w") as file:
		file.write(localCidr)

if domains != oldDomains:
	with open("/var/nomx/domains", "w") as file:
		file.write(domains)

from godaddypy import Client, Account

cur = db.cursor()
cur.execute("SELECT `domain`, `gduser`, `gdpass` FROM `domain` WHERE `domain` != \"ALL\"")
for row in cur.fetchall():
	if row[1] == "":
		continue
	print("[%s] Checking domain %s..." % (datetime.datetime.now().isoformat(), row[0]))
	client = Client(Account(api_key = row[1], api_secret = row[2]))
	try:
		for domain in client.get_domains():
			if row[0].endswith(domain):
				client.delete_records(row[0], name = "mail")
				client.add_record(row[0], {'data': ip, 'name': 'mail', 'ttl': 3600, 'type': 'A'})
				print("[%s] DNS record for mail.%s has been updated with IP %s successfully." % (datetime.datetime.now().isoformat(), row[0], ip))
				time.sleep(10)
				client.delete_records(row[0], name = "localmail")
				client.add_record(row[0], {'data': localIp, 'name': 'localmail', 'ttl': 3600, 'type': 'A'})
				print("[%s] DNS record for localmail.%s has been updated with IP %s successfully." % (datetime.datetime.now().isoformat(), row[0], localIp))
				cur.execute("INSERT INTO `log` (`timestamp`, `username`, `domain`, `action`, `data`) VALUES (NOW(), \"system\", \"%s\", \"godaddy dns synchronization\", \"Successfully updated.\")" % row[0])
	except Exception as e:
		cur.execute("INSERT INTO `log` (`timestamp`, `username`, `domain`, `action`, `data`) VALUES (NOW(), \"system\", \"%s\", \"godaddy dns synchronization\", \"Error, please check logs.\")" % row[0])
		print("[%s] There was an error communicating with GoDaddy: %s" % (datetime.datetime.now().isoformat(), str(e)))