update-dns-pi.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env python2
  2. #
  3. # Copyright (c) 2017-2018 Joe Clarke <jclarke@cisco.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. # NOTE: This script is now obsolete. We no longer use Prime Infra.
  27. import requests
  28. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  29. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  30. import json
  31. import sys
  32. import re
  33. import CLEUCreds
  34. PI = "10.100.253.22"
  35. DNS_BASE = "https://dc1-dns.ciscolive.local:8443/web-services/rest/resource/"
  36. DOMAIN = "ciscolive.local"
  37. CNR_HEADERS = {"authorization": CLEUCreds.JCLARKE_BASIC, "accept": "application/json", "content-type": "application/json"}
  38. PAGE_SIZE = 1000
  39. def get_devs():
  40. global PI, PAGE_SIZE, DOMAIN
  41. url = "https://{}/webacs/api/v1/data/Devices.json?.full=true&.maxResults={}".format(PI, PAGE_SIZE)
  42. headers = {"Connection": "close"}
  43. devices = []
  44. done = False
  45. first = 0
  46. while not done:
  47. code = 401
  48. i = 0
  49. nurl = url + "&.firstResult=" + str(first * PAGE_SIZE)
  50. while code != 200 and i < 10:
  51. response = requests.request("GET", nurl, auth=(CLEUCreds.PI_USER, CLEUCreds.PI_PASS), headers=headers, verify=False)
  52. code = response.status_code
  53. if code != 200:
  54. i += 1
  55. time.sleep(3)
  56. if code == 200:
  57. j = json.loads(response.text)
  58. if int(j["queryResponse"]["@last"]) + 1 == int(j["queryResponse"]["@count"]):
  59. done = True
  60. else:
  61. first += 1
  62. for dev in j["queryResponse"]["entity"]:
  63. dev_dic = {}
  64. if "deviceName" in dev["devicesDTO"]:
  65. dev_dic["name"] = dev["devicesDTO"]["deviceName"]
  66. else:
  67. continue
  68. if not re.search(r"^0", dev_dic["name"]):
  69. continue
  70. dev_dic["ip"] = dev["devicesDTO"]["ipAddress"]
  71. nparts = dev_dic["name"].split("-")
  72. if len(nparts) == 3:
  73. dev_dic["aliases"] = []
  74. dev_dic["name"] = dev_dic["name"].replace(".{}".format(DOMAIN), "")
  75. dev_dic["aliases"].append("-".join(nparts[0:2]) + ".{}.".format(DOMAIN))
  76. dev_dic["aliases"].append(nparts[2] + ".{}.".format(DOMAIN))
  77. devices.append(dev_dic)
  78. return devices
  79. def add_entry(url, hname, dev):
  80. global CNR_HEADERS, DOMAIN
  81. aliases = []
  82. if "aliases" in dev:
  83. aliases = dev["aliases"]
  84. try:
  85. host_obj = {"addrs": {"stringItem": [dev["ip"]]}, "aliases": {"stringItem": []}, "name": hname, "zoneOrigin": DOMAIN}
  86. for alias in aliases:
  87. host_obj["aliases"]["stringItem"].append(alias)
  88. response = requests.request("PUT", url, headers=CNR_HEADERS, json=host_obj, verify=False)
  89. response.raise_for_status()
  90. print("Added entry for {} ==> {} with aliases {}".format(hname, dev["ip"], str(aliases)))
  91. except Exception as e:
  92. sys.stderr.write("Error adding entry for {}: {}\n".format(hname, e))
  93. if __name__ == "__main__":
  94. devs = get_devs()
  95. for dev in devs:
  96. hname = dev["name"].replace(".{}".format(DOMAIN), "")
  97. url = DNS_BASE + "CCMHost" + "/{}".format(hname)
  98. response = requests.request("GET", url, headers=CNR_HEADERS, params={"zoneOrigin": DOMAIN}, verify=False)
  99. if response.status_code == 404:
  100. iurl = DNS_BASE + "CCMHost"
  101. response = requests.request(
  102. "GET", iurl, params={"zoneOrigin": DOMAIN, "addrs": dev["ip"] + "$"}, headers=CNR_HEADERS, verify=False
  103. )
  104. cur_entry = []
  105. if response.status_code != 404:
  106. cur_entry = response.json()
  107. if len(cur_entry) > 0:
  108. print("Found entry for {}: {}".format(dev["ip"], response.status_code))
  109. cur_entry = response.json()
  110. if len(cur_entry) > 1:
  111. print("ERROR: Found multiple entries for IP {}".format(dev["ip"]))
  112. continue
  113. print("Found old entry for IP {} => {}".format(dev["ip"], cur_entry[0]["name"]))
  114. durl = DNS_BASE + "CCMHost" + "/{}".format(cur_entry[0]["name"])
  115. try:
  116. response = requests.request("DELETE", durl, params={"zoneOrigin": DOMAIN}, headers=CNR_HEADERS, verify=False)
  117. response.raise_for_status()
  118. except Exception as e:
  119. sys.stderr.write("Failed to delete stale entry for {} ({})\n".format(cur_entry[0]["name"], dev["ip"]))
  120. continue
  121. add_entry(url, hname, dev)
  122. else:
  123. cur_entry = response.json()
  124. create_new = True
  125. for addr in cur_entry["addrs"]["stringItem"]:
  126. if addr == dev["ip"]:
  127. if "aliases" in dev and "aliases" in cur_entry:
  128. if (len(dev["aliases"]) > 0 and "stringItem" not in cur_entry["aliases"]) or (
  129. len(dev["aliases"]) != len(cur_entry["aliases"]["stringItem"])
  130. ):
  131. break
  132. common = set(dev["aliases"]) & set(cur_entry["aliases"]["stringItem"])
  133. if len(common) != len(dev["aliases"]):
  134. break
  135. create_new = False
  136. break
  137. elif ("aliases" in dev and "aliases" not in cur_entry) or ("aliases" in cur_entry and "aliases" not in dev):
  138. break
  139. else:
  140. create_new = False
  141. break
  142. if create_new:
  143. print("Deleting entry for {}".format(hname))
  144. try:
  145. response = requests.request("DELETE", url, headers=CNR_HEADERS, params={"zoneOrigin": DOMAIN}, verify=False)
  146. response.raise_for_status()
  147. except Exception as e:
  148. sys.stderr.write("Error deleting entry for {}: {}\n".format(hname, e))
  149. add_entry(url, hname, dev)
  150. else:
  151. print("Not creating a new entry for {} as it already exists".format(dev["name"]))