Example #1
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")
Example #2
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])
Example #3
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])
Example #4
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']))
Example #5
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)
Example #6
0
    def test_client_init(self):
        client = Client(self.account)

        print(client.get_domains())
Example #7
0
import logging
import pif
from godaddypy import Client, Account

logging.basicConfig(filename='godaddy.log',
                    format='%(asctime)s %(message)s',
                    level=logging.INFO)

my_acct = Account(api_key='e52xSqLBxqDf_6LNm7ZQzA2gZtPioxPkynu',
                  api_secret='GqwcELGWrvChmkf83XtNan')
client = Client(my_acct)
public_ip = pif.get_public_ip('v4.ident.me')

for dominio in client.get_domains():
    records = client.get_records(dominio, record_type='A')
    logging.debug("Dominio '{0}' Registros DNS: {1}".format(
        dominio, records[0]['data']))
    actual_ip = records[0]['data']
    if public_ip != records[0]['data']:
        client.update_ip(public_ip, domains=dominio)
        client.update_record_ip(public_ip, dominio, 'dynamic', 'A')
        logging.info("Dominio '{0}' Ip Pública configurada a '{1}'".format(
            dominio, public_ip))

actual = client.get_records(dominio, record_type='A')
print("Configuración Final:")
print(actual)
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:
Example #9
0
        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),
                                "iotaa.co.uk", "jenkins", "A"))

print(client.get_records("iotaa.co.uk", record_type="A"))
Example #10
0
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)
Example #11
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)