Script I created to run with a cron and update dnsimple when my public IP changed.

updater.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/python
  2. from dnsimple import DNSimple
  3. from urllib import urlopen
  4. from sys import stderr, exit
  5. from apikey import API_EMAIL, API_KEY
  6. domains = [{"domain": 'jshaver.net', "names": ["", "bc"]},
  7. {"domain": 'theamazingshavers.com', "names": [""]}]
  8. ttl = 600
  9. dns = DNSimple(email=API_EMAIL, api_token=API_KEY)
  10. response = urlopen("http://icanhazip.com/")
  11. if response.getcode() != 200:
  12. stderr.write("Non 200 status when retrieving ip! Status: {}".format(response.getcode()))
  13. exit(-1)
  14. ip = response.readline().rstrip()
  15. def get_a_record(domain, name):
  16. records = dns.records(domain)
  17. for entry in records:
  18. record = entry["record"]
  19. if record["name"] is name and ["record_type"] is 'A':
  20. return record
  21. return None
  22. def update_record(domain, name, record, ip):
  23. new = {"name": name, "content": ip}
  24. response = dns.update_record(domain, record["id"], new)
  25. return response["record"]
  26. def create_record(domain, name, ip):
  27. new = {
  28. "name": name,
  29. "content": ip,
  30. "record_type": "A",
  31. "ttl": ttl}
  32. print new
  33. print domain
  34. response = dns.add_record(domain, new)
  35. return response["record"]
  36. def update_domain_ip(domain, name, ip):
  37. record = get_a_record(domain, name)
  38. if record is None:
  39. return create_record(domain, name, ip)
  40. if record["content"] is ip:
  41. return record
  42. return update_record(record, name, ip)
  43. def main(domainList, ip):
  44. for domain in domainList:
  45. for name in domain["names"]:
  46. update_domain_ip(domain["domain"], name, ip)
  47. main(domains, ip)