Exemplo n.º 1
0
    def print_status(self,eprint):
        #<PyWebDriver> Full refactoring of the function to allow
        # localisation and to make more easy the search of the ip
        ip = get_public_ip()
        eprint.text('\n\n')
        eprint.set(align='center',type='b',height=2,width=2)
        eprint.text(_(u'PyWebDriver Software Status'))
        eprint.text('\n\n')
        eprint.set(align='center')

        if not ip:
            msg = _(
                """ERROR: Could not connect to LAN\n\n"""
                """Please check that your system is correc-\n"""
                """tly connected with a network cable,\n"""
                """ that the LAN is setup with DHCP, and\n"""
                """that network addresses are available""")
            eprint.text(msg)
        else:
            eprint.text(_(u'IP Addresses:') + '\n')
            eprint.text(ip + ' (' + _(u'Public') + ')\n')
            for ifaceName in interfaces():
                pass
                addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
                eprint.text(', '.join(addresses) + ' (' + ifaceName + ')\n')
            eprint.text('\n' + _(u'Port:') + '\n')
            eprint.text(self.port + '\n')

        eprint.text('\n\n')
        eprint.cut()
Exemplo n.º 2
0
def ip_type(proxy, headers=config.headers):
    """ 确定代理ip的类型, 并记录响应时间
    
    :param proxy: 代理ip
    :param headers: 默认headers
    :return:
    """
    if not isinstance(proxy, dict):
        raise Exception("Error, argument error.")

    start_time = time.time()
    proxy_ip = re.search("(\d{1,3}.){3}\d{1,3}", proxy.values()[0]).group()
    headers["User-Agent"] = ua_cls.random
    headers["X_FORWARDED_FOR"] = proxy_ip
    res = requests.get(url=url, headers=headers, proxies=proxy)
    proxy_cst = "%.3f" % (time.time() - start_time)
    http_via = res.headers.get("Via", "").strip()  # HTTP_VIA
    remote_addr = json.loads(res.text).get(
        "origin", "").split(',')[-1].strip()  # REMOTE_ADDR, record the last ip
    http_x_forwarded_for = json.loads(res.text).get(
        "origin", "").strip()  # HTTP_X_FORWARDED_FOR, record all ips
    orig_addr = get_public_ip().strip()  # real ip

    # 代理类型说明:
    # transparent(透明代理), anonymous(匿名代理), elite(高匿代理), nothing(无代理)
    if remote_addr == proxy_ip and http_via != "" and orig_addr in http_x_forwarded_for:
        proxy_type = "transparent"
    elif remote_addr == proxy_ip and http_via != "" and http_x_forwarded_for == proxy_ip:
        proxy_type = "anonymous"
    elif remote_addr == proxy_ip and http_via == "" and http_x_forwarded_for == "":
        proxy_type = "elite"
    else:
        proxy_type = "nothing"

    return proxy_type, proxy_cst
Exemplo n.º 3
0
 def save_plugin_data(self, request=None):
     """
     For showing the weather, we need an IP address. Although we don't make it possible for the user to
     specify it manually, we silently obtain it and save into the plugin data.
     """
     if not self.cleaned_data.get('public_ip', None):
         try:
             self.cleaned_data['public_ip'] = get_public_ip()
         except Exception as e:
             if DEBUG:
                 logger.debug(e)
Exemplo n.º 4
0
 def save_plugin_data(self, request=None):
     """
     For showing the weather, we need an IP address. Although we don't make it possible for the user to
     specify it manually, we silently obtain it and save into the plugin data.
     """
     if not self.cleaned_data.get('public_ip', None):
         try:
             self.cleaned_data['public_ip'] = get_public_ip()
         except Exception as e:
             if DEBUG:
                 logger.debug(e)
Exemplo n.º 5
0
    def get(self):
        """

        :return:
        """
        if self.request.arguments:
            user = self.get_argument('user')
            group = self.get_argument('group')
            fullname = pif.get_public_ip('fullname')
            ModifyEntriesResult = LDAPHandler().modify_entries(
                username=user, groups=group, fullname=fullname)
            self.write(bytes(ModifyEntriesResult) + "\n")
def loop_forever():

    public_ip_cache = False

    # Loop forever
    while True:

        # Go get our current public IP address
        new_ip = False
        while not new_ip:
            try:
                if record_type == 'A':
                    pub_ip = pif.get_public_ip()
                elif record_type == 'AAAA':
                    pub_ip = bytes.decode(url_postget(ipv6_get_api))
                else:
                    logging.error("record type must be 'A' or 'AAAA' .")
                    break

                # Check for valid ip
                try:
                    ipaddress.ip_address(pub_ip)
                    new_ip = pub_ip
                except:
                    logging.error('Got an invalid ip address')
                    logging.debug('ip address {}'.format(pub_ip),
                                  exc_info=True)
            except:
                logging.exception('Got exception getting public IP')

            # Done if we got one
            if new_ip:
                break

            time.sleep(get_ip_wait_sec)

        # If we got the same IP address, we will try again later
        if public_ip_cache != new_ip:
            # Update the records at godaddy
            try:
                worked = update_godaddy_records(new_ip)
                if worked:
                    #cache so we dont try again if everything went good
                    logging.info('new-ip: {}, old-ip: {}'.format(
                        new_ip, public_ip_cache))
                    public_ip_cache = new_ip
            except:
                logging.exception('Got exception updating godaddy records')

        time.sleep(update_interval_sec)
Exemplo n.º 7
0
 def get(self):
     host = get_public_ip()
     msg = Message(
         subject="%s - Daily Summary - %s" % ({{ cookiecutter.project_name}}, time.ctime()),
         sender=("Canna Notifier", "*****@*****.**"),  # sender是一个二元组, 分别为姓名和邮件地址
         recipients=[
             {{ cookiecutter.mail_receiver }}
         ]
     )
     items = []
     msg.html = render_template('email.html', items=items, title="canna.notifier", host=host)
     try:
         mail.send(msg)
     except Exception as e:
         return jsonify(dict(Code=-1, State=e))
     return jsonify(dict(Code=0, State="Ok"))
Exemplo n.º 8
0
def submit(data):
    TO = "*****@*****.**"
    SUBJECT = data['lecture'] + ' HW ' + data['homework_number'] + ' ' + data[
        'student_number']
    TEXT_CC = data['consent'] + data[
        'student_name_surname'] + '\n' + '\n' + "PLATFORM : " + str(
            platform.uname()) + '\n' + "PYTHON VERSION : " + str(
                platform.python_version()) + '\n' + 'IP: ' + str(
                    get_public_ip())

    auth = {}
    auth['user'] = data['user']
    auth['pass'] = data['password']

    msg = MIMEMultipart()
    msg['Subject'] = SUBJECT
    msg['To'] = data['cc']
    attachment = MIMEApplication(open(data['script_name'], "rb").read(),
                                 _subtype="py")
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=data['script_name'])
    msg.attach(attachment)
    msg.attach(MIMEText(TEXT_CC))
    if data['image_name'] != '':
        img = MIMEImage(open(data['image_name'], 'rb').read())
        msg.attach(img)

    # Gmail Sign In
    gmail_sender = auth['user']
    gmail_passwd = auth['pass']

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_sender, gmail_passwd)

    try:
        if data['cc'] != '':
            server.sendmail(gmail_sender, [data['cc']], msg.as_string())
        server.sendmail(gmail_sender, [TO], msg.as_string())
        return 'email sent'
    except:
        return 'error sending mail'
    server.quit()
Exemplo n.º 9
0
def home(request):
    context = {}
    try:
        with open('/proc/uptime', 'r') as f:
            uptime_seconds = float(f.readline().split()[0])
            uptime_string = str(timedelta(seconds = uptime_seconds))
    except:
        uptime_string = 'Not available!'

    if request.GET:
        minutes = int(request.GET.get('minutes'))
        now = datetime.now()
        while (datetime.now()-now).seconds <= (minutes*60):
            generate_load(30)

    context['ip'] = get_public_ip()
    context['uptime'] = uptime_string
    context['hostname'] = socket.gethostname()
    return render(request, 'home.html', context)
Exemplo n.º 10
0
        def printstatus(self, eprint):
            # <PyWebDriver> Full refactoring of the function to allow
            # localisation and to make more easy the search of the ip

            self.open_printer()
            ip = get_public_ip()

            if not ip:
                msg = _("""ERROR: Could not connect to LAN<br/><br/>"""
                        """Please check that your system is correc-<br/>"""
                        """tly connected with a network cable,<br/>"""
                        """ that the LAN is setup with DHCP, and<br/>"""
                        """that network addresses are available""")
                Layout("<div>" + msg + "</div>").format(self)
                self.cut()
            else:
                addr_lines = []
                for ifaceName in interfaces():
                    addresses = [
                        i["addr"] for i in ifaddresses(ifaceName).setdefault(
                            AF_INET, [{
                                "addr": "No IP addr"
                            }])
                    ]
                    addr_lines.append("<p>" + ",".join(addresses) + " (" +
                                      ifaceName + ")" + "</p>")
                msg = _("""
                       <div align="center">
                            <h4>PyWebDriver Software Status</h4>
                            <br/><br/>
                            <h5>IP Addresses:</h5>
                            %s<br/>
                            %s<br/>
                            Port: %i
                       </div>
                """) % (
                    ip + " (" + _(u"Public") + ")",
                    "".join(addr_lines),
                    config.getint("flask", "port"),
                )
                Layout("<div>" + msg + "</div>").format(self)
                self.close()
Exemplo n.º 11
0
        def printstatus(self, eprint):
            #<PyWebDriver> Full refactoring of the function to allow
            # localisation and to make more easy the search of the ip

            self.open_printer()
            ip = get_public_ip()

            if not ip:
                msg = _("""ERROR: Could not connect to LAN<br/><br/>"""
                        """Please check that your system is correc-<br/>"""
                        """tly connected with a network cable,<br/>"""
                        """ that the LAN is setup with DHCP, and<br/>"""
                        """that network addresses are available""")
                self.receipt('<div>' + msg + '</div>')
                self.cut()
            else:
                addr_lines = []
                for ifaceName in interfaces():
                    addresses = [
                        i['addr'] for i in ifaddresses(ifaceName).setdefault(
                            AF_INET, [{
                                'addr': 'No IP addr'
                            }])
                    ]
                    addr_lines.append('<p>' + ','.join(addresses) + ' (' +
                                      ifaceName + ')' + '</p>')
                msg = _(u"""
                       <div align="center">
                            <h4>PyWebDriver Software Status</h4>
                            <br/>
                            <h5>IP Addresses:</h5>
                            %s<br/>
                            %s<br/>
                            Port šđč枊ĐČĆŽ: %i
                       </div>
                """) % (
                    ip + ' (' + _(u'Public') + ')',
                    ''.join(addr_lines),
                    config.getint('flask', 'port'),
                )
                self.receipt(msg)
Exemplo n.º 12
0
    def print_status(self, eprint):
        ip = get_public_ip()
        eprint.text('\n\n')
        eprint.set(align='center', type='b', height=2, width=2)
        eprint.text(_(u'PosBox Status'))
        eprint.text('\n\n')
        eprint.set(align='center')

        if not ip:
            msg = _("""ERROR: Could not connect to LAN\n\n"""
                    """Please check that the PosBox is correc-\n"""
                    """tly connected with a network cable,\n"""
                    """ that the LAN is setup with DHCP, and\n"""
                    """that network addresses are available""")
            eprint.text(msg)
        else:
            eprint.text(_(u'IP Address:') + '\n' + ip + '\n')
            eprint.text('\n' + _(u'Homepage:') + '\n')
            eprint.text('http://' + ip + ':' + str(settings.FLASK_PORT) + '\n')

        eprint.text('\n\n')
        eprint.cut()
Exemplo n.º 13
0
    def post(self):
        """

        :return:
        """
        client = server_instance()
        if self.request.arguments:
            domain = self.get_argument('domain')
            a_record = self.get_argument('a_record')
            publicIP = pif.get_public_ip('ident.me')
            records = client.get_records(domain,
                                         record_type='A',
                                         name=a_record)
            for record in records:
                if str(publicIP) != str(record["data"]):
                    client = server_instance()
                    updateResult = client.update_record_ip(
                        publicIP, domain, a_record, 'A')
                    if updateResult:
                        self.write('Update ended with no Exception.')
                else:
                    self.write('No DNS update needed.')
Exemplo n.º 14
0
    def post(self):
        """

        :return:
        """
        token = server_instance()
        if self.request.arguments:
            domain = self.get_argument('domain')
            a_record = self.get_argument('a_record')
            short_addr = self.get_argument('short_addr')
            if not short_addr:
                short_addr = pif.get_public_ip('ident.me')
            domain_id = DomainID['%s' % domain]
            record_list = {}
            api = RecordList(DomainID['%s' % domain], token=token)
            records = api().get("records")
            len_record = len(list(records))
            for i in range(0, len_record):
                rekey = name = records[i].get('name')
                reid = cordid = records[i].get('id')
                record_list['%s' % rekey] = '%s' % reid
            try:
                record_id = record_list['%s' % a_record]
                api = RecordModify(record_id,
                                   sub_domain=a_record,
                                   record_type="A",
                                   record_line=u'默认'.encode("utf8"),
                                   value=short_addr,
                                   ttl=600,
                                   domain_id=domain_id,
                                   token=token)
                result = api()
                self.write(
                    '{ "errno": "%s", "result": "%d",  "errmsg": "%s" }' %
                    (0, 200, result['status']['message']))
            except Exception as e:
                self.write('{ "errno": "%s", "result": "%d",  "errmsg": "" }' %
                           (0, 500))
Exemplo n.º 15
0
        def printstatus(self,eprint):
            #<PyWebDriver> Full refactoring of the function to allow
            # localisation and to make more easy the search of the ip

            self.open_printer()
            ip = get_public_ip()

            if not ip:
                msg = _(
                    """ERROR: Could not connect to LAN<br/><br/>"""
                    """Please check that your system is correc-<br/>"""
                    """tly connected with a network cable,<br/>"""
                    """ that the LAN is setup with DHCP, and<br/>"""
                    """that network addresses are available""")
                self.receipt('<div>'+msg+'</div>')
                self.cut()
            else:
                addr_lines = []
                for ifaceName in interfaces():
                    addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
                    addr_lines.append(
                        '<p>'+','.join(addresses) + ' (' + ifaceName + ')' + '</p>'
                    )
                msg = _(u"""
                       <div align="center">
                            <h4>PyWebDriver Software Status</h4>
                            <br/>
                            <h5>IP Addresses:</h5>
                            %s<br/>
                            %s<br/>
                            Port šđč枊ĐČĆŽ: %i
                       </div>
                """) % (
                    ip + ' (' + _(u'Public') + ')',
                    ''.join(addr_lines),
                    config.getint('flask', 'port'),
                )
                self.receipt(msg)
Exemplo n.º 16
0
    def print_status(self,eprint):
        ip = get_public_ip()
        eprint.text('\n\n')
        eprint.set(align='center',type='b',height=2,width=2)
        eprint.text(_(u'PosBox Status'))
        eprint.text('\n\n')
        eprint.set(align='center')

        if not ip:
            msg = _(
                """ERROR: Could not connect to LAN\n\n"""
                """Please check that the PosBox is correc-\n"""
                """tly connected with a network cable,\n"""
                """ that the LAN is setup with DHCP, and\n"""
                """that network addresses are available""")
            eprint.text(msg)
        else:
            eprint.text(_(u'IP Address:') + '\n'+ ip +'\n')
            eprint.text('\n' + _(u'Homepage:') + '\n')
            eprint.text('http://'+ip+':' + str(settings.FLASK_PORT) + '\n')

        eprint.text('\n\n')
        eprint.cut()
Exemplo n.º 17
0
def myIp(request):
    ip = get_public_ip()
    html = "<html><body>Welcome, my IP is: " + ip + "</body></html>"
    return HttpResponse(html)
logger.debug('\n')
logger.debug("**********Starting GoDaddy DNS Update**********")

#Retrieve access and secret keys from encrypted file
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:
Exemplo n.º 19
0
def day(request):
    oggi = date.today()
    ip = get_public_ip()
    tmp = {'title': oggi, 'h1': oggi.day, 'p': ip}
    return render(request, 'estesa.html', {'terna': tmp})
Exemplo n.º 20
0
def get_public_ip():
    return pif.get_public_ip()
Exemplo n.º 21
0
def GetIpAddress():
    return pif.get_public_ip()
Exemplo n.º 22
0
def myip(request):
    return HttpResponse("Welcome, my ip is: " + get_public_ip())
Exemplo n.º 23
0
def gethostname():
    try:
        return socket.gethostbyaddr(get_public_ip())[0]
    except:
        return socket.gethostname()
Exemplo n.º 24
0
def get_public_ip():
    return pif.get_public_ip()
Exemplo n.º 25
0
#!/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()
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:
Exemplo n.º 27
0
def get_global_ip():
    #pip install pif(public ip)
    from pif import get_public_ip
    return (get_public_ip())
Exemplo n.º 28
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:
                print(date + ' Update for the domain ' + domain + ' record ' +
Exemplo n.º 29
0
def gethostname():
    return socket.gethostbyaddr(get_public_ip())[0]
Exemplo n.º 30
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)
Exemplo n.º 31
0
 def get_ip(self):
     self.debug_file.write("[debug] checking public ip \n")
     IP = get_public_ip()
     return IP
Exemplo n.º 32
0
 def get_ip(self):
     self.debug_file.write("[debug] checking public ip \n")
     IP = get_public_ip()
     return IP
Exemplo n.º 33
0
#!/usr/bin/env python
 
import logging
import pif
from pygodaddy import GoDaddyClient
 
logging.basicConfig(filename='godaddy.log', format='%(asctime)s %(message)s', level=logging.INFO)
GODADDY_USERNAME="******";
GODADDY_PASSWORD="******";
client = GoDaddyClient()
client.login(GODADDY_USERNAME, GODADDY_PASSWORD)


logging.info(client.find_domains())

for domain in client.find_domains():
    dns_records = client.find_dns_records(domain)
    public_ip = pif.get_public_ip()
    logging.debug("Domain '{0}' DNS records: {1}".format(domain, dns_records))
    if public_ip != dns_records[0].value:
        client.update_dns_record(domain, public_ip)
        logging.info("Domain '{0}' public IP set to '{1}'".format(domain, public_ip))
Exemplo n.º 34
0
config.read(CONFIG_PATH)

try:
    DOMAINS = config.items('DOMAINS')
    RECORD_TYPE = config['RECORD']['Record_Type']
    RECORD_NAME = config['RECORD']['Record_Name']
    API_KEY = config['CREDENTIALS']['GoDaddyAPI_Key']
    API_SECRET = config['CREDENTIALS']['GoDaddyAPI_Secret']

except KeyError:
    logger.error('Error loading ini: check ini exists and settings are correct')
    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"]:
Exemplo n.º 35
0
from godaddypy import Client, Account

import os

key = os.environ['GODADDY_KEY']
secret_key = os.environ['GODADDY_SECRET']
domain_list = os.environ['GODADDY_DOMAIN_LIST'].split(',')
a_record_list = os.environ['GODADDY_A_RECORD_LIST'].split(',')
create_missing_records = os.environ.get('GODADDY_CREATE_MISSING_RECORDS', True)

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

publicIP = False
while not publicIP:
  publicIP = pif.get_public_ip()

for domain in domain_list:
  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,
                        }
Exemplo n.º 36
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)