コード例 #1
0
    def test_account_without_delegate(self):
        _PRIVATE_KEY = 'blahdeyblah'
        _PUBLIC_KEY = 'hooeybalooooooeryasdfasdfsdfs'

        acct = Account(api_key=_PUBLIC_KEY, api_secret=_PRIVATE_KEY)

        assert 'Authorization' in acct.get_headers()
        assert acct.get_headers(
        )['Authorization'] == Account._SSO_KEY_TEMPLATE.format(
            api_secret=_PRIVATE_KEY, api_key=_PUBLIC_KEY)
コード例 #2
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)
コード例 #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")
コード例 #4
0
 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)
コード例 #5
0
ファイル: site_api.py プロジェクト: dashage/domainManager
 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"}
コード例 #6
0
ファイル: pushIP.py プロジェクト: MimTiller/IP-Updater
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
コード例 #7
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))
コード例 #8
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'
コード例 #9
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)
コード例 #10
0
def server_instance():
    """

    :return:
    """
    api_key = ''
    api_secret = ''
    server = Account(api_key=api_key, api_secret=api_secret)
    client = Client(server)
    return client
コード例 #11
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])
コード例 #12
0
ファイル: update.py プロジェクト: kel-lit/GoDaddyDNSUpdater
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)
コード例 #13
0
ファイル: dns.py プロジェクト: adamzev/burlap
    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
コード例 #14
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']))
コード例 #15
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'
    })
コード例 #16
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'
        }]
コード例 #17
0
    def test_account_with_delegate(self):
        _DELEGATE_ID = '1234987234jdsfasdf'
        _PRIVATE_KEY = 'blahdeyblah'
        _PUBLIC_KEY = 'hooeybalooooooeryasdfasdfsdfs'

        acct = Account(api_key=_PUBLIC_KEY,
                       api_secret=_PRIVATE_KEY,
                       delegate=_DELEGATE_ID)

        assert 'X-Shopper-Id' in acct.get_headers()
        assert 'Authorization' in acct.get_headers()
        assert acct.get_headers()['X-Shopper-Id'] == _DELEGATE_ID
        assert acct.get_headers(
        )['Authorization'] == Account._SSO_KEY_TEMPLATE.format(
            api_secret=_PRIVATE_KEY, api_key=_PUBLIC_KEY)
コード例 #18
0
ファイル: main.py プロジェクト: emme1444/dns-updater
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)
コード例 #19
0
API_KEY = os.getenv('GDKEY')
API_SECRET = os.getenv('GDSECRET')
CERTBOT_DOMAIN = os.getenv('CERTBOT_DOMAIN')

LOG_FILE = script_dir + "/clean.log"

if os.path.exists(LOG_FILE):
    os.remove(LOG_FILE)

logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s',
                    level=logging.ERROR,
                    filename=LOG_FILE)

try:
    my_acct = Account(api_key=API_KEY, api_secret=API_SECRET)
    client = Client(my_acct)
except Exception as err:
    logging.error(f"Account config error: {err}")


def findTXTID(data):
    ids = []
    for record in data:
        if "_acme-challenge" in record['name']:
            ids.append(record['name'])
    return ids


try:
    records = client.get_records(CERTBOT_DOMAIN, record_type='TXT')
コード例 #20
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
コード例 #21
0
def get_client():
    account = Account(get_json('config.json')['api_key'], get_json('config.json')['api_secret'])
    return Client(account)
コード例 #22
0
update_now = False

if 'last_update' in config:
    last_update = datetime.strptime(config['last_update'], '%Y-%m-%d %H:%M:%S.%f')
    if now - last_update > dt:
        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')
コード例 #23
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)
コード例 #24
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)
コード例 #25
0
ファイル: update-dns.py プロジェクト: timcoote/CICD
]
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),
                                "iotaa.co.uk", "jenkins", "A"))
コード例 #26
0
ファイル: update-dns.py プロジェクト: timcoote/CICD
 def setUp(self):
     self.client = Client(
         Account(api_key=os.environ['godaddy_key'],
                 api_secret=os.environ['godaddy_secret']))
コード例 #27
0
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:
コード例 #28
0
ファイル: godaddy.py プロジェクト: csnyder78/ArecCreate
#!/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'
})
コード例 #29
0
ファイル: updateRecord.py プロジェクト: dark-vex/godaddypy
#!/usr/bin/env python3

# 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')
コード例 #30
0
from godaddypy import Client, Account
import time

try:
    certDOMAIN = os.environ['CERTBOT_DOMAIN']
    certVALIDATION = os.environ['CERTBOT_VALIDATION']
except:
    # called for pre-hook
    sys.exit(0)

# Remember to set your parameters
paramAPIKEY = 'godaddy api key'
paramAPISECRET = 'godaddy api secret'
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'