diff-route-tables.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2017-2019 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. import paramiko
  27. import os
  28. from sparker import Sparker, MessageType
  29. import time
  30. from subprocess import Popen, PIPE, call
  31. import shlex
  32. import re
  33. import json
  34. import argparse
  35. import CLEUCreds
  36. import shutil
  37. from cleu.config import Config as C
  38. routers = {}
  39. commands = {"ip_route": "show ip route", "ipv6_route": "show ipv6 route"}
  40. cache_dir = "/home/jclarke/routing-tables"
  41. ROUTER_FILE = "/home/jclarke/routers.json"
  42. WEBEX_ROOM = "Core Alarms"
  43. if __name__ == "__main__":
  44. parser = argparse.ArgumentParser(description="Usage:")
  45. # script arguments
  46. parser.add_argument("--git-repo", "-g", metavar="<GIT_REPO_PATH>", help="Optional path to a git repo to store updates")
  47. parser.add_argument("--git-branch", "-b", metavar="<BRANCH_NAME>", help="Branch name to use to commit in git")
  48. parser.add_argument(
  49. "--notify",
  50. "-n",
  51. metavar="<ROUTER_NAME>",
  52. help="Only notify on routers with a given name (can be specified more than once)",
  53. action="append",
  54. )
  55. args = parser.parse_args()
  56. spark = Sparker(token=CLEUCreds.SPARK_TOKEN)
  57. ssh_client = paramiko.SSHClient()
  58. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  59. try:
  60. fd = open(ROUTER_FILE, "r")
  61. routers = json.load(fd)
  62. fd.close()
  63. except Exception as e:
  64. print("ERROR: Failed to load routers file {}: {}".format(ROUTER_FILE, e))
  65. do_push = False
  66. for router, ip in routers.items():
  67. try:
  68. ssh_client.connect(
  69. ip, username=CLEUCreds.NET_USER, password=CLEUCreds.NET_PASS, timeout=60, allow_agent=False, look_for_keys=False,
  70. )
  71. chan = ssh_client.invoke_shell()
  72. for fname, command in commands.items():
  73. output = ""
  74. try:
  75. chan.sendall("term length 0\n")
  76. chan.sendall("term width 0\n")
  77. chan.sendall("{}\n".format(command))
  78. i = 0
  79. while i < 10:
  80. if chan.recv_ready():
  81. break
  82. time.sleep(0.5)
  83. i += 1
  84. while chan.recv_ready():
  85. output = output + chan.recv(65535).decode("utf-8")
  86. except Exception as ie:
  87. print("Failed to get {} from {}: {}".format(command, router, ie))
  88. continue
  89. fpath = "{}/{}-{}".format(cache_dir, fname, router)
  90. curr_path = fpath + ".curr"
  91. prev_path = fpath + ".prev"
  92. fd = open(curr_path, "w")
  93. output = re.sub(r"\r", "", output)
  94. output = re.sub(r"([\d\.]+) (\[[^\n]+)", "\\1\n \\2", output)
  95. fd.write(re.sub(r"(via [\d\.]+), [^,\n]+([,\n])", "\\1\\2", output))
  96. fd.close()
  97. if os.path.exists(prev_path):
  98. proc = Popen(shlex.split("/usr/bin/diff -b -B -w -u {} {}".format(prev_path, curr_path)), stdout=PIPE, stderr=PIPE,)
  99. out, err = proc.communicate()
  100. rc = proc.returncode
  101. if rc != 0:
  102. if (args.notify and router in args.notify) or not args.notify:
  103. spark.post_to_spark(
  104. C.WEBEX_TEAM,
  105. WEBEX_ROOM,
  106. "Routing table diff ({}) on **{}**:\n```\n{}\n```".format(
  107. command, router, re.sub(cache_dir + "/", "", out.decode("utf-8"))
  108. ),
  109. MessageType.BAD,
  110. )
  111. time.sleep(1)
  112. if args.git_repo:
  113. if os.path.isdir(args.git_repo):
  114. try:
  115. gfile = re.sub(r"\.curr", ".txt", os.path.basename(curr_path))
  116. shutil.copyfile(curr_path, args.git_repo + "/" + gfile)
  117. os.chdir(args.git_repo)
  118. call("git add {}".format(gfile), shell=True)
  119. call('git commit -m "Routing table update" {}'.format(gfile), shell=True)
  120. do_push = True
  121. except Exception as ie:
  122. print("ERROR: Failed to commit to git repo {}: {}".format(args.git_repo, ie))
  123. else:
  124. print("ERROR: Git repo {} is not a directory".format(args.git_repo))
  125. # print('XXX: Out = \'{}\''.format(out))
  126. os.rename(curr_path, prev_path)
  127. except Exception as e:
  128. ssh_client.close()
  129. print("Failed to get routing tables from {}: {}".format(router, e))
  130. continue
  131. ssh_client.close()
  132. if do_push:
  133. if not args.git_branch:
  134. print("ERROR: Cannot push without a branch")
  135. else:
  136. os.chdir(args.git_repo)
  137. call("git pull origin {}".format(args.git_branch), shell=True)
  138. call("git push origin {}".format(args.git_branch), shell=True)