tool-to-librenms.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2017-2024 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. from __future__ import print_function
  27. import requests
  28. from requests.packages.urllib3.exceptions import InsecureRequestWarning # type: ignore
  29. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  30. import json
  31. import sys
  32. import time
  33. from subprocess import run
  34. import shlex
  35. import re
  36. import CLEUCreds # type: ignore
  37. from cleu.config import Config as C # type: ignore
  38. CACHE_FILE = "/home/jclarke/monitored_devs.json"
  39. def get_devs():
  40. url = "http://{}/get/switches/json".format(C.TOOL)
  41. devs = []
  42. response = requests.request("GET", url)
  43. code = 200
  44. code = response.status_code
  45. if code == 200:
  46. j = response.json()
  47. for dev in j:
  48. if dev["IPAddress"] == "0.0.0.0" or not dev["Reachable"]:
  49. continue
  50. if not re.search(r"^[0-9A-Za-z]{3}-", dev["Hostname"]):
  51. continue
  52. if (
  53. re.search(r".*CORE.*", dev["Hostname"], flags=re.I)
  54. or re.search(r"^WLC", dev["Hostname"], flags=re.I)
  55. or re.search(r".*MER[124]-dist.*", dev["Hostname"], flags=re.I)
  56. ):
  57. continue
  58. devs.append(dev)
  59. return devs
  60. def delete_device(dev):
  61. res = run(shlex.split("ssh -2 {} /usr/local/www/librenms/delhost.php {}".format(C.MONITORING, dev)), capture_output=True)
  62. return res
  63. if __name__ == "__main__":
  64. devs = {}
  65. force = False
  66. changed_devs = False
  67. if len(sys.argv) == 2:
  68. if sys.argv[1] == "-f":
  69. force = True
  70. try:
  71. with open(CACHE_FILE, "r") as fd:
  72. devs = json.load(fd)
  73. except Exception as e:
  74. print(f"Failed to open {CACHE_FILE}: {e}")
  75. tdevs = get_devs()
  76. i = 0
  77. for tdev in tdevs:
  78. i += 1
  79. if tdev["AssetTag"] in list(devs.keys()) and devs[tdev["AssetTag"]] != tdev["Hostname"]:
  80. print("=== Deleting device {} from LibreNMS ({} / {}) ===".format(tdev["Hostname"], i, len(tdevs)))
  81. res = delete_device(devs[tdev["AssetTag"]])
  82. if res.returncode != 0:
  83. print(
  84. "\n\n***WARNING: Failed to remove LibreNMS device for {}: out='{}', err='{}'".format(
  85. devs[tdev["AssetTag"]], res.stdout.decode("utf-8").strip(), res.stderr.decode("utf-8").strip()
  86. )
  87. )
  88. print("=== DONE. ===")
  89. changed_devs = True
  90. del devs[tdev["AssetTag"]]
  91. time.sleep(3)
  92. if tdev["AssetTag"] not in list(devs.keys()) or force:
  93. if force:
  94. print("=== Deleting device {} from LibreNMS ({} / {}) ===".format(tdev["Hostname"], i, len(tdevs)))
  95. res = delete_device(tdev["Hostname"])
  96. if res.returncode != 0:
  97. print(
  98. "\n\n***WARNING: Failed to remove LibreNMS device {}: out='{}', err='{}'".format(
  99. tdev["Hostname"], res.stdout.decode("utf-8").strip(), res.stderr.decode("utf-8").strip()
  100. )
  101. )
  102. print("=== DONE. ===")
  103. time.sleep(3)
  104. url = "https://librenms." + C.DNS_DOMAIN + "/api/v0/inventory/" + tdev["Hostname"]
  105. try:
  106. response = requests.request("GET", url, headers={"X-Auth-Token": CLEUCreds.LIBRENMS_TOKEN}, verify=False)
  107. response.raise_for_status()
  108. devs[tdev["AssetTag"]] = tdev["Hostname"]
  109. changed_devs = True
  110. continue
  111. except Exception:
  112. if not response or response.status_code != 400:
  113. text = ""
  114. if response:
  115. text = response.text
  116. print(f"Error retrieving device status for {tdev['Hostname']} from LibreNMS: {response.text}")
  117. print("=== Adding device {} to LibreNMS ({} / {}) ===".format(tdev["Hostname"], i, len(tdevs)))
  118. res = run(
  119. shlex.split(
  120. "ssh -2 {} /usr/local/www/librenms/addhost.php {} ap v3 CLEUR {} {} sha aes".format(
  121. C.MONITORING, tdev["Hostname"], CLEUCreds.SNMP_AUTH_PASS, CLEUCreds.SNMP_PRIV_PASS
  122. )
  123. ),
  124. capture_output=True,
  125. )
  126. if res.returncode != 0:
  127. print(
  128. "\n\n***ERROR: Failed to add {} to LibreNMS: out='{}', err='{}'".format(
  129. tdev["Hostname"], res.stdout.decode("utf-8").strip(), res.stderr.decode("utf-8").strip()
  130. )
  131. )
  132. continue
  133. print("=== DONE. ===")
  134. changed_devs = True
  135. devs[tdev["AssetTag"]] = tdev["Hostname"]
  136. if changed_devs:
  137. with open(CACHE_FILE, "w") as fd:
  138. json.dump(devs, fd)