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)
Beispiel #2
0
 def __init__(self, api_key, api_secret):
     self.api_key = api_key
     self.api_secret = api_secret
     my_acct = Account(api_key, api_secret)
     self.__client = Client(my_acct)
     self.Authorization = "sso-key %s:%s" % (self.api_key, self.api_secret)
     self.headers = {"Authorization": self.Authorization, "accept": "application/json","Content-Type": "application/json"}
Beispiel #3
0
def main():
    """ Find IPs from web host DNS and update godaddy DNS.
    """
    config = _config()

    resolver = Resolver()
    resolver.nameservers = config['initial_nameservers']
    LOG.debug("Resolving namdservers %s", config['nameservers'])
    nameservers = [resolver.address(_) for _ in config['nameservers']]

    resolver.nameservers = nameservers

    addresses = {}
    for domain in config['domains']:
        addresses[domain] = resolver.address(domain)
    LOG.debug("Found addresses: %s", addresses)

    account = Account(**config['credentials'])
    client = Client(account)
    domains = client.get_domains()

    for domain, address in addresses.items():
        if domain not in domains:
            raise ValueError("%s not in client list of domains" % domain)
        current = client.get_records(domain)[0]['data']
        if current != address:
            LOG.info('updating %s (%s -> %s)', domain, current, address)
            client.update_record_ip(address, domain, '@', 'A')
        else:
            LOG.info('Record up-to-date %s (%s)', domain, address)
    LOG.debug("complete")
Beispiel #4
0
def update_dns_record(domain, record_type, record_name, ip_address, api_key,
                      api_secret, logger):

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

    records = userClient.get_records(domain,
                                     record_type=record_type,
                                     name=record_name)

    # dudes = [x["name"] for x in records_of_type_a]

    if not records:
        logger.error("No {} / {} record found to update.".format(
            record_type, record_name))
        return

    for record in records:
        logger.info("Updating record with name '{}'".format(record["name"]))
        result = userClient.update_record_ip(ip_address,
                                             domain,
                                             name=record["name"],
                                             record_type=record_type)
        logger.info("Updated '{}' with result : {}".format(
            record["name"], result))
Beispiel #5
0
def update_godaddy_ip(ip):
    try:
        godaddydomain = Account(api_key=godaddy_key, api_secret=godaddy_secret)
        client = Client(godaddydomain)
        client.update_ip(ip, domains=[domainname])
    except:
        pass
Beispiel #6
0
 def get_client(self, GoDaddyConfig):
     if GoDaddyConfig.api_key == '' or GoDaddyConfig.secret_key == '':
         print(f'{color.red}[!] Add GoDaddy keys to config file{color.end}')
         exit()
     acct = Account(api_key=GoDaddyConfig.api_key,
                    api_secret=GoDaddyConfig.secret_key)
     return Client(acct)
Beispiel #7
0
    def setup_class(cls):
        cls.logger = logging.getLogger(cls.__name__)
        cls.logger.setLevel(logging.INFO)

        cls.account = Account('', '')
        # Create a Client and override the API to use the test API
        cls.client = Client(cls.account, log_level=logging.WARNING)
        cls.client.API_TEMPLATE = 'https://api.ote-godaddy.com/v1'
Beispiel #8
0
    def showQuickEditWindow(self):

        #The QuickEditWindow is not instantiated until the first time
        #that user wants to show it. So here we create it if it does
        #not exist.
        if self.quick_edit_window == None:
            settings_dir, config_pathname = self.get_config_pathname()
            try:
                with open(config_pathname.as_posix(), "r") as f:
                    s = f.read()
                    d = json.loads(s)
                    my_acct = Account(api_key=d.get("PUBLIC_KEY"),
                                      api_secret=d.get("SECRET_KEY"))

                    client = Client(my_acct)
                #TODO: Should also add some sanity check in here to make
                #sure the key works.

            except Exception as e:
                """
                If there is no configuration found, then we can not have 
                client connection to GoDaddy via the godaddyapp.client. 
                
                So we need to ask the client to configure.
                """

                self.api_key_entry_window = ApiKeyEntryWindow()
                self.api_key_entry_window.show()

                client = None

            self.quick_edit_window = DNSQuickEditWindow(client)
        """ 
        Move the DNSQuickEditWindow to the bottom left corner of 
        the monitor where the taskbar Icon is. This uses the screenNumber 
        function to determine which screen the mouse is current active on. 
        It then finds the screenGeometry of that monitor. 
        """

        frameGm = self.quick_edit_window.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().availableGeometry(
            screen).bottomRight()
        frameGm.moveBottomRight(centerPoint)

        monitor = QApplication.desktop().availableGeometry(screen)

        print(monitor.width(), monitor.height())
        x1, y1, x2, y2 = frameGm.getCoords()

        x_offset = (2 / 100) * monitor.width()
        y_offset = (10 / 100) * monitor.height()

        print(self.quick_edit_window.width(), self.quick_edit_window.height())
        self.quick_edit_window.move(x1 - x_offset, y1 - y_offset)
Beispiel #9
0
def server_instance():
    """

    :return:
    """
    api_key = ''
    api_secret = ''
    server = Account(api_key=api_key, api_secret=api_secret)
    client = Client(server)
    return client
Beispiel #10
0
def main():
    r = requests.get(config["public_ip"])
    current_ip = r.json()["ip"]
    my_acct = Account(api_key=config["key"], api_secret=config['secret'])
    client = Client(my_acct)
    my_domains = client.get_domains()
    daddy_ip = client.get_a_records(my_domains[0])[0]['data']
    if current_ip != daddy_ip:
        client.update_ip(current_ip, domains=[my_domains[0]])
    else:
        print "Your Public IP is %s and GoDaddy A record is %s for the domain %s" % (
            current_ip, daddy_ip, my_domains[0])
Beispiel #11
0
def update(config):
    public_ip = requests.get('http://ip.42.pl/raw').text

    account = Account(api_key=config.key, api_secret=config.secret)
    client = Client(account)

    record = client.get_records(config.domain, record_type='A')
    if record[0]['data'] != public_ip:
        print('Updating IP from {} to {}'.format(record[0]['data'], public_ip))
        client.update_ip(public_ip, domains=[config.domain])

    time.sleep(60)
Beispiel #12
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 #13
0
def main():
    pp = pprint.PrettyPrinter(indent=4)

    my_acct = Account(api_key=keyring.get_password('godaddy', 'apikey'), \
                api_secret=keyring.get_password('godaddy', 'apisecret'))
    client = Client(my_acct)

    domains = client.get_domains()
    print("{}".format(domains))

    for dom in domains:
        r = client.get_domain_info(dom)
        print("{}:".format(r['domain']), end=" ")
        if r['status'] == 'CANCELLED':
            cprint("{}".format(r['status']), "red")
        elif r['status'] == 'ACTIVE':
            cprint("{}".format(r['status']), "green")
            records = client.get_records(r['domain'])
            #pp.pprint(records)
            has_caa = False
            has_mxs = False
            has_soa = False
            has_cnames = False
            has_as = False
            has_nss = False
            for R in records:
                if R['type'] == 'A':
                    has_as = True
                elif R['type'] == 'SOA':
                    has_soa = True
                elif R['type'] == 'CAA':
                    has_caa = True
                elif R['type'] == 'CNAME':
                    has_cnames = True
                elif R['type'] == 'NS':
                    has_nss = True
                elif R['type'] == 'MX':
                    has_mxs = True
                else:
                    cprint("Unrecognized type: {}".format(R['type']), \
                            "magenta")
            print("\tA: {}, CNAME: {}, SOA: {}, CAA: {}, MX: {}, NS: {}"\
                    .format(has_as, has_cnames, has_soa, has_caa, has_mxs, \
                        has_nss))
        else:
            print("Unrecognized domain status: {}: {}".format(\
                r['domain'], r['status']))
Beispiel #14
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 #15
0
    def setup_class(cls):
        cls.logger = logging.getLogger(cls.__name__)
        cls.logger.setLevel(logging.INFO)

        cls.account = Account('', '')
        # Create a Client and override the API to use the test API
        cls.client = Client(cls.account, log_level=logging.WARNING)
        cls.client.API_TEMPLATE = 'https://api.ote-godaddy.com/v1'

        cls.fake_records = [{
            'name': 'test1',
            'ttl': 3600,
            'data': '127.0.0.1',
            'type': 'A'
        }, {
            'name': 'test2',
            'ttl': 3600,
            'data': '192.168.0.1',
            'type': 'A'
        }]
Beispiel #16
0
def main():
    account = Account(api_key=config.GODADDY_KEY,
                      api_secret=config.GODADDY_SECRET)
    client = Client(account)

    # Check that user owns the specified domain
    domains = client.get_domains()
    print("INFO: Checking target domain ownership.")
    if domains.count(config.GODADDY_DOMAIN) != 1:
        raise AssertionError("ERROR: User must own the domain specified.")

    print("INFO: Retrieving currentIP.")
    currentIP = client.get_records(
        config.GODADDY_DOMAIN, record_type="A", name="@")[0]["data"].strip()
    print("INFO: currentIP retrieved.")

    # main update loop
    while True:
        try:
            print("INFO: Retrieving publicIP.")
            publicIP = requests.get("http://ip.42.pl/raw").text.strip()
            print("INFO: publicIP retrieved.")
        except:
            print("ERROR: Could not fetch public IP!")

        print("INFO: Checking publicIP against currentIP")
        if publicIP != currentIP:
            print(
                f"INFO: IP out of date. Updating current IP to: {publicIP}.")
            try:
                client.update_ip(publicIP, domains=[
                    config.GODADDY_DOMAIN])
                currentIP = publicIP
                print(f"INFO: IP update successful.")
            except:
                print("ERROR: Could not update IP!")

        # Pause execution for UPDATE_INTERVAL seconds.
        time.sleep(config.UPDATE_INTERVAL)
Beispiel #17
0
# Full package imports
import sys
# Get current time and date
import time

import pif
# Partial imports
from godaddypy import Client, Account

domain = 'example.com'
a_record = 'www'
date = strftime("%d/%m/%Y %H:%M:%S")

userAccount = Account(api_key='YOUR_KEY', api_secret='YOUR_SECRET')
userClient = Client(userAccount)
publicIP = pif.get_public_ip('ident.me')

# This fix an issue when the IP address cannot be retreived
if publicIP is None or publicIP is False:
    print(date + ' Unable to retrieve an IP from pif, exiting... ' + domain +
          ' record ' + a_record)
    sys.exit()

try:
    records = userClient.get_records(domain, name=a_record, record_type='A')
    for record in records:
        if publicIP != record["data"]:
            updateResult = userClient.update_record_ip(publicIP, domain,
                                                       a_record, 'A')
            if updateResult is True:
Beispiel #18
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'
})
Beispiel #19
0
def get_godaddy_ip():
    godaddydomain = Account(api_key=godaddy_key, api_secret=godaddy_secret)
    client = Client(godaddydomain)
    r = client.get_records(domainname, record_type='A', name='@')
    return r
Beispiel #20
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)))
"""
Simple script to update GoDaddy DNS records.
Add this script to the crontab to run it regularly.
"""
from requests import get
from godaddypy import Client, Account

# ---  start configs. ---

api_key = 'GODADDY API KEY'
api_secret = 'GODADDY API SECRET'

domain = 'alfcorp.org'
name = '@'

# ---  end configs. ---

ip = get('https://api.ipify.org').text

account = Account(api_key=api_key, api_secret=api_secret)
client = Client(account)
ret = client.update_record_ip(ip, domain, name, 'A')
assert ret
Beispiel #22
0
def get_client():
    account = Account(get_json('config.json')['api_key'], get_json('config.json')['api_secret'])
    return Client(account)
Beispiel #23
0
#!/usr/bin/env python
## auther honux, update the dns records of godaddy, you must keep the redis running and config.ini exist.
from godaddypy import Client, Account
import time, logging, redis
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
config = dict(cfg.items('update_records_godaddy'))
pool = redis.ConnectionPool(host='127.0.0.1',port=6379,decode_responses=True)
r = redis.Redis(connection_pool=pool)
logging.basicConfig(filename="godaddy.log", filemode="w", format="%(asctime)s %(name)s:%(levelname)s:%(message)s", datefmt="%d-%M-%Y %H:%M:%S", level=logging.DEBUG)
api_key = config['vu_key']
api_secret = config['vu_secret']
my_acct = Account(api_key, api_secret)
delegate_acct = Account(api_key, api_secret, delegate='DELEGATE_ID')
client = Client(my_acct)
delegate_client = Client(delegate_acct)

def adddns(asd):
    logging.info("update %s!" % asd)
    try:
        t = client.get_domain_info(asd)
    except Exception as e:
        r.lpush("godaddy_err", asd)
        logging.exception("%s domain has ERR" % asd)
    else:
        p = ['IVY.NS.CLOUDFLARE.COM', 'JAY.NS.CLOUDFLARE.COM']
        if t.get('nameServers') == p:
            client.update_domain(asd, nameServers = ['ns23.domaincontrol.com', 'ns24.domaincontrol.com'])
            logging.error("%s ns has changed, plase wait to effective." % asd)
            time.sleep(3)
Beispiel #24
0
#!/usr/bin/env python

# pip install godaddypy

from godaddypy import Client, Account

myAccount = Account(api_key='Your production api key',
                    api_secret='Your production api secret')
client = Client(myAccount)
print(client.get_domains())
Beispiel #25
0
def LoginAccount():
    acct = Account(api_key='?', api_secret='?')
    client = Client(acct)
    return client
import pif, sys, os.path
from godaddypy import Client, Account

api_key = "ENTER_API_KEY_HERE"
secret_key = "ENTER_SECRET_KEY_HERE"

domain = 'edennimni.me'

acc = Account(api_key=api_key, api_secret=secret_key)
client = Client(acc)

public_ipv4 = pif.get_public_ip()

if client is None:
    print("[] Could not open the specified account.")
if client.get_domains() is None:
    print("[] Could not edit an account with no domains available.")
if public_ipv4 is None:
    print("[] Could not fetch public ip, please try again later.")

try:
    for records in client.get_records(domain, record_type='A'):
        if public_ipv4 == records["data"]:
            print("[] IPv4 is already updated.")
        else:
            if client.update_record_ip(public_ipv4, domain, records["name"],
                                       'A'):
                print("[] IPv4 has been updated successfuly.")
            else:
                print("[] IPv4 has not been updated successfuly.")
except Exception as e:
Beispiel #27
0
]
for instance_id, instance in ec2info.items():
    for key in attributes:
        print("{0}: {1}".format(key, instance[key]))
    print("------")

for x in running_instances:
    print(x.network_interfaces_attribute[0]['Ipv6Addresses'])

# values before start:
# (update) Tims-MacBook-Pro-2:godaddy tim$ python x.py
# ['iotaa.co', 'iotaa.co.uk', 'iotaa.org']
# [{'type': 'A', 'name': '@', 'data': '139.59.135.120', 'ttl': 600}, {'type': 'A', 'name': 'demo', 'data': '192.168.43.20', 'ttl': 600}, {'type': 'A', 'name': 'hubcentral', 'data': '52.56.237.214', 'ttl': 3600}]

client = Client(
    Account(api_key=os.environ['godaddy_key'],
            api_secret=os.environ['godaddy_secret']))

print(client.get_domains())
print(client.get_records("iotaa.co.uk", record_type="A"))

# coote.org: temp for cert signing with letsencrypt
# print (client.update_record_ip ("87.81.133.180", "iotaa.co.uk", "demo", "A"))
# ip address handed out by hotspot on phone
# print (client.update_record_ip ("192.168.43.20", "iotaa.co.uk", "demo", "A"))
# an ec2 instance
print(client.update_record_ip("35.177.48.101", "iotaa.co.uk", "demo", "A"))

for ri in running_instances:
    print(
        client.update_record_ip("{}".format(ri.public_ip_address),
Beispiel #28
0
    quit()

try:
    logger.debug('Getting Public IP')
    publicIP = get_public_ip()
    logger.info('Got Public IP: ' + publicIP)

except Exception as e:
    logger.error('Error Getting Public IP: ' + e.__str__())
    sys.exit()

for DOMAIN in DOMAINS:
    try:
        logger.debug('Getting GoDaddy Records for ' + DOMAIN[1])
        godaddy_acct = Account(api_key=API_KEY, api_secret=API_SECRET)
        client = Client(godaddy_acct)
        records = client.get_records(DOMAIN[1], record_type=RECORD_TYPE, name=RECORD_NAME)
        try:
            for record in records:
                if publicIP != record["data"]:
                    updateResult = client.update_record_ip(publicIP, DOMAIN[1], name=RECORD_NAME,
                                                           record_type=RECORD_TYPE)
                    if updateResult is True:
                        logger.info('DNS Record Updated for ' + DOMAIN[1] + ':' + record["data"] + ' to ' + publicIP)
                else:
                    logger.info('DNS Record Update not Needed for ' + DOMAIN[1] + ':' + publicIP)

        except Exception as e:
            logger.error('Error Trying to Update DNS Record' + e.__str__())
            sys.exit()
Beispiel #29
0
def update_ip(config_file, force):
    """Update the IP address for the configured domains/subdomains

    Parameters:
     - config_file: Open file or file-like object configuration file
     - force: boolean flag for forcing updates (True => force update)

    Returns:
     - updated: bool indicating whether the IP address was updated
     - myip: str containing the current IP address
     - domains: list of updated domains (eg. ["[sub1,sub2].[example.com]"])
    """
    # Load the configuration file
    try:
        config = yaml.load(config_file)
    except (yaml.MarkedYAMLError, yaml.YAMLError) as e:
        raise ConfigError("Error: {}".format(e))

    # Check the supplied log path
    log_path = config.get("log_path")
    if log_path:
        # Make sure that the log path exists and is writable
        try:
            touch(log_path)
        except PermissionError:
            msg = "Error: Insufficient permissions to write log to '{}'.".format(
                log_path)
            raise PermissionError(
                msg)  # Currently no log, so just raise an exception

        # Define the logging function
        def write_log(msg):
            now = datetime.datetime.now().isoformat(' ', timespec='seconds')
            with open(log_path, 'a') as f:
                f.write("[{now}]: {msg}\n".format(now=now, msg=msg))
    else:
        # No log file specified, so disable logging
        def write_log(msg):
            pass

    # Check the supplied cache path
    cache_path = config.get("cache_path")
    if cache_path:
        # Make sure that the log path exists and is writable
        try:
            touch(cache_path)  # Create the file if necessary
        except PermissionError:
            msg = "Error: Insufficient permissions to write to cache ({}).".format(
                cache_path)
            write_log(msg)
            raise PermissionError(msg)

        # Define the caching functions
        def write_cache(ip_addr):
            now = datetime.datetime.now().isoformat(' ', timespec='seconds')
            with open(cache_path, 'w') as f:
                f.write("[{}]: {}".format(now, ip_addr))

        def read_cache():
            with open(cache_path, "r") as f:
                cached = f.readline()
            return (cached[1:20], cached[23:])  # date_time, ip_addr
    else:
        # No cache file specified, so disable caching and warn the user!
        msg = (
            "Warning: No cache file specified, so the IP address will always be submitted "
            "as if new - this could be considered abusive!")
        write_log(msg)
        warnings.warn(msg)

        # Define the caching functions
        def write_cache(ip_addr):
            pass  # Don't write to cache

        def read_cache():
            return (None, None)

    # Get IPv4 address
    myip = pif.get_public_ip("v4.ident.me")  # Enforce IPv4 (for now)

    if not myip:
        msg = "Error: Failed to determine IPv4 address"
        write_log(msg)
        raise ConnectionError(msg)

    # Check whether the current IP is equal to the cached IP address
    date_time, cached_ip = read_cache()
    if force:
        write_log("Info: Performing forced update")
    elif myip == cached_ip:
        # Already up-to-date, so log it and exit
        write_log(
            "Success: IP address is already up-to-date ({})".format(myip))
        return (False, myip, None)
    else:
        write_log("Info: New IP address detected ({})".format(myip))

    # Get API details
    api_key = config.get("api_key")
    api_secret = config.get("api_secret")

    # Check that they have values
    missing_cred = []
    if not api_key:
        missing_cred.append("'api_key'")
    if not api_secret:
        missing_cred.append("'api_secret'")

    if missing_cred:
        msg = "Error: Missing credentials - {} must be specified".format(
            " and ".join(missing_cred))
        write_log(msg)
        raise ConfigError(msg)

    # Initialise the connection classes
    account = Account(api_key=config.get("api_key"),
                      api_secret=config.get("api_secret"))
    client = Client(account,
                    api_base_url=config.get("api_base_url",
                                            "https://api.godaddy.com"))

    # Check that we have a connection and get the set of available domains
    try:
        available_domains = set(client.get_domains())
    except BadResponse as e:
        msg = "Error: Bad response from GoDaddy ({})".format(e._message)
        write_log(msg)
        raise BadResponse(msg)

    # Make the API requests to update the IP address
    failed_domains = set(
    )  # Stores a set of failed domains - failures will be tolerated but logged
    succeeded_domains = []
    forced = "forcefully " if force else ""

    for target in config.get("targets", []):
        try:
            target_domain = target["domain"]
        except KeyError:
            msg = "Error: Missing 'domain' for target in configuration file"
            write_log(msg)
            raise ConfigError(msg)

        if isinstance(target_domain, str):
            target_domain = {target_domain}  # set of one element
        else:
            target_domain = set(target_domain)  # set of supplied targets

        unknown_domains = target_domain - available_domains
        failed_domains.update(unknown_domains)

        domains = list(target_domain
                       & available_domains)  # Remove unknown domains
        if not domains:
            continue  # No known domains, so don't bother contacting GoDaddy

        subdomains = target.get(
            "alias",
            "@")  # Default to no subdomain (GoDaddy uses "@" for this)

        try:
            update_succeeded = client.update_ip(myip,
                                                domains=domains,
                                                subdomains=subdomains)
        except BadResponse as e:
            msg = "Error: Bad response from GoDaddy ({})".format(e._message)
            write_log(msg)
            raise BadResponse(msg)

        if update_succeeded:
            succeeded_domains.append("{subs}.{doms}".format(subs=subdomains,
                                                            doms=domains))
            write_log("Success: IP address {}updated to {} for {}.".format(
                forced, myip, succeeded_domains[-1]))
        else:
            msg = "Error: Unknown failure for (domain(s): {doms}, alias(es): {subs})".format(
                doms=target_domain, subs=subdomains)
            write_log(msg)
            raise BadResponse(msg)

    if failed_domains:
        msg = "Warning: The following domains were not found {}".format(
            failed_domains)
        write_log(msg)
        warnings.warn(msg)

    # Write the new IP address to the cache and return
    write_cache(myip)
    return (True, myip, succeeded_domains)
Beispiel #30
0
 def setUp(self):
     self.client = Client(
         Account(api_key=os.environ['godaddy_key'],
                 api_secret=os.environ['godaddy_secret']))