lost-device.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #!/usr/local/bin/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. import sys
  27. import sparker
  28. import re
  29. import requests
  30. import json
  31. import logging
  32. import traceback
  33. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  34. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  35. import CLEUCreds
  36. TEAM_NAME = 'CL18-Infra_team'
  37. ROOM_NAME = 'Lost Devices'
  38. CMX_URL = 'http://10.100.253.13:8002/api/v0.1/cmx'
  39. HEADERS = {
  40. 'Accept': 'image/jpeg, application/json'
  41. }
  42. OUR_TENANT = 31
  43. if __name__ == '__main__':
  44. spark = sparker.Sparker(True)
  45. print('Content-type: application/json\r\n\r\n')
  46. output = sys.stdin.read()
  47. j = json.loads(output)
  48. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s : %(message)s',
  49. filename='/var/log/lost-device.log', level=logging.DEBUG)
  50. logging.debug(json.dumps(j, indent=4))
  51. if not 'rule' in j or j['rule']['name'] != 'LostDevicesAlert':
  52. logging.debug('Dropping message for {}'.format(j['rule']['name']))
  53. print(json.dumps({'result': 'ignore'}))
  54. sys.exit(0)
  55. message = j['message'] + '\n\n'
  56. cmxres = {}
  57. msg = message
  58. for asset in j['assets']:
  59. location = 'UNKNOWN'
  60. for state in asset['state']:
  61. if state['key'] == 'location':
  62. if 'hierarchy' in state['value']:
  63. location = state['value']['hierarchy'].replace('!', ' > ')
  64. break
  65. msg += '* Device **{}** with MAC _{}_ is back in **{}**\n'.format(
  66. asset['name'], asset['macAddresses'][0].lower(), location)
  67. try:
  68. response = requests.request('GET', CMX_URL, params={'mac': asset['macAddresses'][
  69. 0].lower(), 'marker': 'green', 'size': 1440}, headers=HEADERS, stream=True)
  70. response.raise_for_status()
  71. except Exception as e:
  72. logging.error('Failed to get result from CMX: {}'.format(e))
  73. continue
  74. if response.headers.get('content-type') == 'application/json':
  75. continue
  76. cmxres[asset['name']] = response.raw.data
  77. spark.post_to_spark(TEAM_NAME, ROOM_NAME, msg)
  78. for cmx in cmxres:
  79. spark.post_to_spark_with_attach(TEAM_NAME, ROOM_NAME, 'Location of {}'.format(
  80. cmx), cmxres[cmx], '{}_location.jpg'.format(cmx.replace(' ', '_')), 'image/jpeg')
  81. print(json.dumps({'result': 'success'}))