コード例 #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")
コード例 #2
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))
コード例 #3
0
"""
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
コード例 #4
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)
コード例 #5
0
# Full package imports
import sys

import pif
# Partial imports
from godaddypy import Client, Account

domain = 'example.com'
a_record = 'www'

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

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,
                                                       name=a_record,
                                                       record_type='A')
            if updateResult is True:
                print('Update ended with no Exception.')
        else:
            print('No DNS update needed.')
except:
    print(sys.exc_info()[1])
    sys.exit()
コード例 #6
0
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:
    print(e)
    sys.exit()
コード例 #7
0
    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()

    except Exception as e:
        logger.error('Error Getting GoDaddy Records: ' + e.__str__())

logger.info("Code Executed in %s Seconds", (time.time() - start_time))
コード例 #8
0
logger.debug("Decrypting access key")
access_key = decrypt_key(AKEY, AKEY_FILE)
logger.debug("Decrypting secret key")
secret_key = decrypt_key(SKEY, SKEY_FILE)

#Set account information for GoDaddy API call
my_acct = Account(api_key=access_key, api_secret=secret_key)
client = Client(my_acct)

#Get public IP
logger.debug('Getting Public IP address of local network')
public_ip = get_public_ip()

#Get current DNS record
logger.debug("Getting current DNS record from GoDaddy")
dns_record = client.get_records(DOMAIN, record_type='A', name=DOMAIN_NAME)
godaddy_dns = dns_record[0]['data']

#Update DNS record only if public ip doesn't match DNS record
logger.debug(
    "Checking if Public IP matches GoDaddy DNS record and updating if not")
if godaddy_dns != public_ip:
    client.update_record_ip(public_ip, DOMAIN, DOMAIN_NAME, 'A')
    logger.info(
        "Updated Public IP address in GoDaddy from {0} to {1}. ".format(
            godaddy_dns, public_ip))
else:
    logger.info(
        'Public IP address {0} did not change. GoDaddy DNS was not updated & DNS IP address is still: {1}'
        .format(public_ip, godaddy_dns))
コード例 #9
0
        # subdomains_tmp will contain the subdomains to be created
        # after the current registered subdomains are updated
        subdomains_tmp = list(subdomains)

        records = userClient.get_records(domain, record_type=record_type)
        for record in records:
            if record["name"] in subdomains:
                print(record["name"])
                subdomains_tmp.remove(record["name"])
                if publicIP == record["data"]:
                    updateResult = True
                else:
                    updateResult = userClient.update_record_ip(
                        publicIP,
                        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,
コード例 #10
0
import os
import urllib.request
from dotenv import load_dotenv
from godaddypy import Client, Account

load_dotenv()

with urllib.request.urlopen('https://api.ipify.org') as response:
    ip = response.read()
    ip = str(ip, 'utf-8')

public_ip = 'public_ip.txt'
ip_file = open(public_ip, 'r')
old_ip = ip_file.readline()

if ip != old_ip:
    new_ip = open(public_ip, 'w')
    new_ip.write(ip)
    new_ip.close()

    account = Account(api_key=os.getenv('API_KEY'),
                      api_secret=os.getenv('API_SECRET'))
    client = Client(account)

    client.update_record_ip(ip, os.getenv('DOMAIN_NAME'),
                            os.getenv('DOMAIN_RECORD'), 'A')
コード例 #11
0
#Check if cache file exists
if path.exists("/cache.txt"):
    print(now + 'Cached IP file exists, comparing current public IP')
    cacheFile = open('/cache.txt', 'r')
    cachedIP = cacheFile.read()
    if cachedIP == currentPublicIP:
        print(now + 'Update not needed.')
    else:
        #Use GoDaddyPy to interact with GoDaddy API
        print(now + 'Public IP has changed, updating now!')
        my_acct = Account(api_key=apiKey, api_secret=secret)
        client = Client(my_acct)
        for singledomain in subdomains:
            #Update all subdomains if current public IP not the same as cached
            time.sleep(1)
            client.update_record_ip(currentPublicIP, domain, singledomain, 'A')
        print(now + 'Records updated!')
    cacheFile.close()

else:
    #First run, create cache.txt
    print(
        now +
        'Cached IP file does not exist, creating and storing current public IP'
    )
    newCacheFile = open('/cache.txt', 'w')
    newCacheFile.write(currentPublicIP)
    newCacheFile.close()

    my_acct = Account(api_key=apiKey, api_secret=secret)
    client = Client(my_acct)
コード例 #12
0
    key = f.read()

#create godaddy object used for retrieving dns info and updating
if secret is not None and key is not None:
    account = Account(api_key=key, api_secret=secret)
else:
    raise Exception('api secret or key was None')

client = Client(account)

#infinite loop to check if the dynamic ip has changed, and if so then update dns records
while True:
    #get the current public ip
    ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
    for domain in domains:
        record = client.get_records(domain, record_type='A', name='@')
        current_ip = record[0].get('data')
        if current_ip != ip:
            result = client.update_record_ip(ip, domain, '@', 'A')
            if result:
                print('Update successful!')
            else:
                print('error')
        else:
            print('nothing to update')
    time.sleep(5)




コード例 #13
0
ファイル: updateReccord.py プロジェクト: getSurreal/godaddypy
#!/usr/bin/env python3

# Full package imports
import pif, sys

# Partial imports
from godaddypy import Client, Account

domain = 'example.com'
a_record = 'www'

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

try:
    currentIP = userClient.get_record(domain, a_record, 'A')
    if (publicIP != currentIP["data"]):
        updateResult = userClient.update_record_ip(publicIP, domain, a_record, 'A')
        if updateResult is True:
            print('Update ended with no Exception.')
    else:
        print('No DNS update needed.')
except:
    print(sys.exc_info()[1])
    sys.exit()
コード例 #14
0
ファイル: updateRecord.py プロジェクト: dark-vex/godaddypy
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:
                print(date + ' Update for the domain ' + domain + ' record ' +
                      a_record + ' was ended with no Exception.')
        else:
            print(date + ' No DNS update needed for the domain ' + domain +
                  ' record ' + a_record)
except:
    print(sys.exc_info()[1])
    sys.exit()
コード例 #15
0
ファイル: update-dns.py プロジェクト: timcoote/CICD
    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"))

# instant hack
#print (client.add_record ('iotaa.co.uk', {'data': '34.241.193.240', 'name': 'elk', 'ttl': 600, 'type': 'A'}))
コード例 #16
0
  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()


コード例 #17
0
                    dest='PUBLIC_KEY',
                    action='store',
                    help="Specify Public Key")
parser.add_argument("-s",
                    "--secretkey",
                    dest='SECRET_KEY',
                    action='store',
                    help="Specify Private Key")
parser.add_argument("-c",
                    "--csv",
                    dest='csv',
                    action='store',
                    help="CSV file path")

args = parser.parse_args()

PUBLIC_KEY = args.PUBLIC_KEY
SECRET_KEY = args.SECRET_KEY

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

file = open((args.csv), newline='')
reader = csv.reader(file)
next(reader)

for line in reader:
    ip, domain, name, recordtype = line
    client.update_record_ip(ip, domain, name, recordtype)
    print("Sucessfully updated", name + "." + domain + ",", ip + ",",
          recordtype, "Record")