diff-route-tables.py 7.3 KB

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