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
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])
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)
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])
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)
update_now = True else: update_now = True if 'last_ip' in config: if my_ip != config['last_ip']: update_now = True if update_now: my_acct = Account(api_key=config['key'], api_secret=config['secret_key']) client = Client(my_acct) domain = config['domain'] sub = config['sub-domain'] print(now.strftime('%Y-%m-%d %H:%M:%S.%f')) if not client.update_ip(my_ip, domains=[domain], subdomains=[sub]): print("ERROR UPDATING DOMAIN!") else: print("Domain updated successfully!") print("Current domain info:") print("\t{0}".format(client.get_records(domain))) config['last_update'] = now.strftime('%Y-%m-%d %H:%M:%S.%f') config['last_ip'] = my_ip with open(args.config, 'w') as f: json.dump(config, f, indent=2)
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)
public_ip = r.text logging.debug(u'Public IP of the AWS instance: ' + public_ip) my_acc = Account( api_key = config.get('GoDaddy', 'api_key'), api_secret = config.get('GoDaddy', 'api_secret')) client = Client(my_acc) a_records = client.get_a_records(MY_DOMAIN) for d in a_records: if d[u'name'] == MY_SUBDOMAIN: current_record = d[u'data'] break if current_record == '': logging.error(u'GoDaddy DNS record for subdomain not found') raise ValueError(u'I can\'t find current DNS record') else: logging.debug(u'Current DNS record: ' + current_record) if public_ip == current_record: logging.debug(u'Public IP and current DNS record are the same (not needed to update)') else: logging.debug(u'We need to update current DNS record') # uncomment string below for record updating client.update_ip(public_ip, domains=[MY_DOMAIN], subdomains=[MY_SUBDOMAIN])
public_ip = r.text logging.debug(u'Public IP of the AWS instance: ' + public_ip) my_acc = Account(api_key=config.get('GoDaddy', 'api_key'), api_secret=config.get('GoDaddy', 'api_secret')) client = Client(my_acc) a_records = client.get_a_records(MY_DOMAIN) for d in a_records: if d[u'name'] == MY_SUBDOMAIN: current_record = d[u'data'] break if current_record == '': logging.error(u'GoDaddy DNS record for subdomain not found') raise ValueError(u'I can\'t find current DNS record') else: logging.debug(u'Current DNS record: ' + current_record) if public_ip == current_record: logging.debug( u'Public IP and current DNS record are the same (not needed to update)' ) else: logging.debug(u'We need to update current DNS record') # uncomment string below for record updating client.update_ip(public_ip, domains=[MY_DOMAIN], subdomains=[MY_SUBDOMAIN])
#!/usr/bin/python import sys, pif, datetime, time, logging from godaddypy import Client, Account class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) while (1): try: nowtime = datetime.datetime.now() my_acct = Account(api_key='KEY', api_secret='SECRET') client = Client(my_acct) pubip = pif.get_public_ip() godaddydns = client.get_records("DOMAIN.COM")[-1]['data'] if pubip != godaddydns: client.update_ip(pubip, domains=['pickel.me']) print( "{} :: DNS Record updated [{}]".format(nowtime, pubip)) # else: # print("{} :: DNS Record is already updated".format(nowtime)) time.sleep(60) except: None
import socket from godaddypy import Client, Account ip_addr = "114.114.114.114" api_url = 'https://api.godaddy.com/v1/domains/wangxidi.xyz/records' my_acct = Account(api_key='9ZpSAWHNdgi_9AhPY28hRQ8pheBoNarWk', api_secret='MYBoT7zYoSxRNV4v91Z4CN') client = Client(my_acct) def get_host_ip(): """ 查询本机ip地址 :return: """ try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0] finally: s.close() return ip client.update_ip(get_host_ip(), domains=['wangxidi.xyz']) r = client.get_records('wangxidi.xyz', record_type='A') print(r)
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)