diff-route-tables.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/env python2
  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
  29. import time
  30. from subprocess import Popen, PIPE
  31. import shlex
  32. import re
  33. import json
  34. import CLEUCreds
  35. routers = {}
  36. commands = {
  37. 'ip_route': 'show ip route',
  38. 'ipv6_route': 'show ipv6 route'
  39. }
  40. cache_dir = '/home/jclarke/routing-tables'
  41. ROUTER_FILE = '/home/jclarke/routers.json'
  42. SPARK_TEAM = 'CL19 NOC Team'
  43. SPARK_ROOM = 'Core Alarms'
  44. if __name__ == '__main__':
  45. spark = Sparker(token=CLEUCreds.SPARK_TOKEN)
  46. ssh_client = paramiko.SSHClient()
  47. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  48. try:
  49. fd = open(ROUTER_FILE, 'r')
  50. routers = json.load(fd)
  51. fd.close()
  52. except:
  53. pass
  54. for router, ip in routers.items():
  55. try:
  56. ssh_client.connect(ip, username=CLEUCreds.NET_USER, password=CLEUCreds.NET_PASS,
  57. timeout=60, allow_agent=False, look_for_keys=False)
  58. chan = ssh_client.invoke_shell()
  59. for fname, command in commands.items():
  60. output = ''
  61. try:
  62. chan.sendall("term length 0\n")
  63. chan.sendall("term width 0\n")
  64. chan.sendall("{}\n".format(command))
  65. i = 0
  66. while i < 10:
  67. if chan.recv_ready():
  68. break
  69. time.sleep(.5)
  70. i += 1
  71. while chan.recv_ready():
  72. output = output + chan.recv(65535)
  73. except Exception as ie:
  74. print('Failed to get {} from {}: {}'.format(
  75. command, router, ie))
  76. continue
  77. fpath = '{}/{}-{}'.format(cache_dir, fname, router)
  78. curr_path = fpath + '.curr'
  79. prev_path = fpath + '.prev'
  80. fd = open(curr_path, 'w')
  81. output = re.sub(r'\r', '', output)
  82. output = re.sub(r'([\d\.]+) (\[[^\n]+)',
  83. '\\1\n \\2', output)
  84. fd.write(
  85. re.sub(r'(via [\d\.]+), [^,\n]+([,\n])', '\\1\\2', output))
  86. fd.close()
  87. if os.path.exists(prev_path):
  88. proc = Popen(
  89. shlex.split('/usr/bin/diff -E -b -B -w -u {} {}'.format(prev_path, curr_path)), stdout=PIPE, stderr=PIPE)
  90. out, err = proc.communicate()
  91. rc = proc.returncode
  92. if rc != 0:
  93. spark.post_to_spark(
  94. SPARK_TEAM, SPARK_ROOM, '**ALERT**: Routing table diff ({}) on **{}**:\n```\n{}\n```'.format(command, router, re.sub(cache_dir + '/', '', out)))
  95. time.sleep(1)
  96. #print('XXX: Out = \'{}\''.format(out))
  97. os.rename(curr_path, prev_path)
  98. except Exception as e:
  99. ssh_client.close()
  100. print('Failed to get routing tables from {}: {}'.format(router, e))
  101. continue
  102. ssh_client.close()