Advertisement
Guest User

input_module_log_analytics.py

a guest
Jul 15th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.96 KB | None | 0 0
  1. import adal
  2. import datetime
  3. import json
  4. import os
  5. import sys
  6. import time
  7. import requests
  8. from splunklib.modularinput import *
  9.  
  10. def validate_input(helper, definition):
  11. inputs=helper.get_input_stanza()
  12. for input_name, input_item in inputs.iteritems():
  13. start_date = str(input_item["start_date"])
  14. try:
  15. valid_date = datetime.datetime.strptime(start_date, '%d/%m/%Y %H:%M:%S')
  16. except ValueError:
  17. helper.log_error("Start date must be in the format of dd/mm/yyyy hh:mm:ss")
  18. pass
  19.  
  20. def collect_events(helper, ew):
  21.  
  22. # Go through each input for this modular input
  23. inputs=helper.get_input_stanza()
  24. for input_name, input_item in inputs.iteritems():
  25. # Get the values, cast them as floats
  26. resource_group = str(input_item["resource_group"])
  27. workspace = str(input_item["workspace_id"])
  28. query = str(input_item["log_analytics_query"])
  29. subscription_id = str(input_item["subscription_id"])
  30. tenant_id = str(input_item["tenant_id"])
  31. application_id = str(input_item["application_id"])
  32. application_key = str(input_item["application_key"])
  33. event_lag = int(float(input_item["event_delay_lag_time"]))
  34.  
  35. # Date and delta
  36. if helper.get_check_point(input_name):
  37. start_datetime = datetime.datetime.strptime(helper.get_check_point(input_name),'%d/%m/%Y %H:%M:%S')
  38. else:
  39. start_datetime = datetime.datetime.strptime(str(input_item['start_date']),'%d/%m/%Y %H:%M:%S')
  40. now = datetime.datetime.utcnow() - datetime.timedelta(minutes=event_lag)
  41. now_dt = now.replace(microsecond=0)
  42.  
  43. # URLs for authentication
  44. authentication_endpoint = 'https://login.microsoftonline.com/'
  45. resource = 'https://api.loganalytics.us/'
  46.  
  47. # Get access token
  48. context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
  49. token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.us/', application_id, application_key)
  50. access_token = token_response.get('accessToken')
  51.  
  52. # Add token to header
  53. headers = {
  54. "Authorization": 'Bearer ' + access_token,
  55. "Content-Type":'application/json'
  56. }
  57.  
  58. # URLs for retrieving data
  59. uri_base = 'https://api.loganalytics.us/'
  60. uri_api = 'v1/'
  61. uri_workspace = 'workspaces/' + workspace + '/'
  62. uri_area = "query"
  63. uri = uri_base + uri_api + uri_workspace + uri_area
  64.  
  65. # Build search parameters from query details
  66. search_params = {
  67. "query": query,
  68. "timespan": start_datetime.strftime('%Y-%m-%dT%H:%M:%S') + '/' + now_dt.strftime('%Y-%m-%dT%H:%M:%S')
  69. }
  70.  
  71. # Send post request
  72. response = requests.post(uri,json=search_params,headers=headers)
  73.  
  74. # Response of 200 if successful
  75. if response.status_code == 200:
  76. # If debug, log event
  77. helper.log_debug('OMSInputName="' + str(input_name) + '" status="' + str(response.status_code) + '" step="Post Query" search_params="' + str(search_params) + "'")
  78. # Parse the response to get the ID and status
  79. data = response.json()
  80. else:
  81. # Request failed
  82. helper.log_error('OMSInputName="' + str(input_name) + '" status="' + str(response.status_code) + '" step="Post Query" response="' + str(response.text) + '"')
  83.  
  84. #Building proper json format from original request
  85. #First loop checks how many events returned is in response
  86. for i in range(len(data["tables"][0]["rows"])):
  87. data1 = "{"
  88. #This nested loop goes through each field, in each event, and concatenates the field name to the field value
  89. for n in range(len(data["tables"][0]["rows"][i])):
  90. field = str(data["tables"][0]["columns"][n]["name"])
  91. value = str(data["tables"][0]["rows"][i][n]).replace('"',"'").replace("\\", "\\\\").replace("None", "").replace("\r\n","")
  92. if value == "":
  93. continue
  94. else:
  95. data1 += '"%s":"%s",' % (field, value)
  96. data1 += "}"
  97. data1 = data1.replace(",}", "}")
  98. event = Event()
  99. event.stanza = input_name
  100. event.data = data1
  101. ew.write_event(event)
  102.  
  103. #Delta
  104. state = now_dt.strftime("%d/%m/%Y %H:%M:%S")
  105. helper.save_check_point(input_name, state)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement