Skip to content

Instantly share code, notes, and snippets.

@rafalw
Last active February 25, 2019 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafalw/a8dd819ae7cccd2438e24bf5a8bc6058 to your computer and use it in GitHub Desktop.
Save rafalw/a8dd819ae7cccd2438e24bf5a8bc6058 to your computer and use it in GitHub Desktop.
Aktualizacja pozyskiwanego dynamicznie zewnętrznego adresu IP przez serwis dnsomatic.com należący do OpenDNS (CISCO)
from sys import argv
from io import BytesIO
from pycurl import Curl
from pycurl import error
import urllib.parse
# Pozyskiwanie globalnego adresu IP
# Adres użyty jako parametr domyślny zwraca wiersz CSV – drugie pole to nasz globalny IP
def get_ip(url_api = 'http://ip4only.me/api/'):
my_ip = BytesIO()
c = Curl()
c.setopt(c.URL, url_api)
c.setopt(c.WRITEDATA, my_ip)
try:
c.perform()
except error as e:
print("Błąd: \"" + e.args[1] +"\"")
return None
else:
# Uwaga: poniższe wiersze są ściśle dostosowane do odpowiedzi
# zwracanej przez serwis o adresie umieszczonym jako domyślna wartość
# parametru url_api;
# w przypadku konieczności użycia innego serwisu/API należy oczywiście te wiersze zmienić!
ip_list = my_ip.getvalue().decode('UTF-8').split(',')
if len(ip_list) > 1:
ip_addr = ip_list[1] # drugie pole – adres IP
else:
ip_addr = None
c.close()
my_ip.close()
return ip_addr
# Aktualizacja adresu IP w serwisie dnsomatic.com
def update_dnsomatic(user, passwd, domain):
# Kodowanie znaków na potrzeby adresów URL:
# kropki – np. w adresie email i adresie IP – trzeba zastąpić "ręcznie"
# (przynajmniej w Pythonie 3.5.2)
user = urllib.parse.quote(user).replace('.', '%2e')
passwd = urllib.parse.quote(passwd).replace('.', '%2e')
domain = urllib.parse.quote(domain).replace('.', '%2e')
ip_addr = get_ip()
if ip_addr:
ip_addr = ip_addr.replace('.', '%2e')
response = BytesIO()
c = Curl()
# Format URL aktualizacji – patrz API dnsomatic.com
c.setopt(c.URL, "http://" + user + ":" + passwd + "@updates.dnsomatic.com/nic/update?hostname=" + domain + "&myip=" + ip_addr)
c.setopt(c.WRITEDATA, response)
try:
c.perform()
except error as e:
print("Błąd: \"" + e.args[1] +"\"")
return None
else:
resp = response.getvalue().decode('UTF-8')
c.close()
response.close()
return resp
else:
return None
if __name__ == "__main__":
if len(argv) < 4:
print("Prawidłowe wywołanie programu:\n")
print("dnsomatic-update.py <user> <passwd> <domain>\n")
else:
print("Próba aktualizacji adresu IP w serwisie dnsomatic.com...")
resp_service = update_dnsomatic(argv[1], argv[2], argv[3])
if resp_service:
print("Odpowiedź serwisu: " + resp_service)
else:
print("Próba nieudana.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment