Guest User

Untitled

a guest
May 22nd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.69 KB | None | 0 0
  1. import requests
  2. from jira import JIRA
  3. from datetime import datetime, timedelta
  4. import csv
  5. import getpass
  6. import sys
  7. import config
  8. from jira.exceptions import JIRAError
  9.  
  10. #Processing files
  11. TEMP_FILE = "output.txt"
  12. JIRA_OUTPUT_FILE="Jira_output.txt"
  13. Jira_log = "Jira_log.txt"
  14.  
  15. out_file = open(TEMP_FILE,"w")
  16. out_file.write("|")
  17.  
  18.  
  19. with open( Jira_log, "wb") as logfile:
  20. # Adjust the date
  21. scandate = datetime.today() - timedelta(days=config.n)
  22. scandate = str(scandate.date())
  23. logfile.write(("Scandate is taken as %s \n" % scandate).encode())
  24.  
  25. #Fetch and process data for Prod
  26. # Arg_prod
  27. length_prod = len(config.Keywordlist_Prod)
  28.  
  29. #Add conditional statement
  30. if (length_prod == 0):
  31. print("No scan Arguments provided in config.py for PROD")
  32. check_EMPTY_PROD = True
  33. logfile.write("No scan Arguments provided in config.py for PROD \n".encode())
  34. else:
  35. arg_prod = ""
  36. for i in range(0, length_prod - 1):
  37. arg_prod = arg_prod + config.Keywordlist_Prod[i] + "|"
  38. arg_prod = arg_prod + config.Keywordlist_Prod[(length_prod - 1)]
  39.  
  40. logfile.write("Fetching results from PROD....\n".encode())
  41.  
  42. # Url for ADDM Appliance
  43. url = config.url_prod
  44.  
  45. # Add API TOKEN in headers
  46. headers = {
  47.  
  48. 'Accept': 'application/json' ,
  49. 'Authorization': 'Bearer Mzo1M2U1ZTAzNWRkZWRiZGRlMDg0NjA3MjgwMWNjMWQzZjphcGlfdXNlcjowLTIwZWM2NDQyMDU4YWNmZDc4ZjRiMDI3ZWUwNjBmZmYwZTgxZjVmODFjYjk3ZmU4Y2IxZDAwNmQ5MjkwZTY4Yzk='
  50. }
  51.  
  52. # Search query for fetching data
  53. params = {
  54.  
  55. 'query': "SEARCH DiscoveryRun WHERE ( label matches '" + arg_prod + "') AND endtime IS DEFINED AND (cancelled or 'No') matches 'No' AND starttime >=parseLocalTime('" + scandate + "')" + config.query_prod,
  56. 'limit': 1000
  57.  
  58. }
  59. print("Fetching Data from PROD. Please wait....! ")
  60. try:
  61. r = requests.get(url=url, params=params, headers=headers)
  62. except requests.exceptions.Timeout:
  63. print("Connection Timed out!")
  64. except requests.exceptions.TooManyRedirects:
  65. print("Too Many redirects")
  66. except requests.exceptions.RequestException as e:
  67. print("Unable to access the Url. \nPlease ensure you are connected to vpn!\n")
  68. logfile.write(("Error reported: %s" %e).encode())
  69. sys.exit(1)
  70. #Response recived in json format
  71. json = r.json()
  72. results_prod = json[0]['results']
  73. headings_prod = json [0]['headings']
  74.  
  75.  
  76.  
  77. # load data to intermediate output file
  78. ##out_file = open(TEMP_FILE,"w")
  79. if len(results_prod) != 0:
  80. check_EMPTY_PROD = False
  81. out_file.write("*Data from PROD* \n")
  82. out_file.write(','.join(headings_prod))
  83. out_file.write('\n')
  84. for item in results_prod:
  85. out_file.write(",".join(map(str, item)))
  86. out_file.write('\n')
  87. else:
  88. check_EMPTY_PROD = True
  89. print("Error:No Data found in PROD")
  90. logfile.write("Error:No Data found in PROD \n".encode())
  91. out_file.close()
  92.  
  93. #Fetch and process data for CERT
  94. # Arg_cert
  95. length_cert = len(config.Keywordlist_Cert)
  96. if (length_cert == 0):
  97. print("No scan Arguments provided in config.py for CERT")
  98. check_EMPTY_CERT = True
  99. logfile.write("No scan Arguments provided in config.py for CERT \n".encode())
  100. else:
  101. arg_cert = ""
  102. for i in range(0, length_cert - 1):
  103. arg_cert = arg_cert + config.Keywordlist_Cert[i] + '|'
  104. arg_cert = arg_cert + config.Keywordlist_Cert[(length_cert - 1)]
  105.  
  106. logfile.write("Fetching results from CERT....\n".encode())
  107.  
  108. #Url for ADDM Appliance
  109. url = config.url_cert
  110.  
  111. #Add API TOKEN in headers
  112. headers = {
  113.  
  114. 'Accept': 'application/json',
  115. 'Authorization': 'Bearer MzoyYzY3Y2QzNWRkZTUyZWYxMWFkODA3MjgwM2Q3MDdkZDphcGlfdXNlcjowLTRiZDcyYjNmMDhjNzA1NjgwOGUwMTlhMDJmYzhhNTY2M2U2ZDU2ODE0YTEzODEzMWQzNTA3MmQzYTliYjc4ZTQ='
  116. }
  117.  
  118. #Search query for fetching data
  119. params = {
  120.  
  121. 'query': "SEARCH DiscoveryRun WHERE ( label matches '" + arg_cert + "') AND endtime IS DEFINED AND (cancelled or 'No') matches 'No' AND starttime >=parseLocalTime('" + scandate + "')" + config.query_cert ,
  122. 'limit': 1000
  123.  
  124. }
  125. print("Fetching data from CERT. Please wait....!")
  126. try:
  127. r = requests.get(url=url, params=params, headers=headers)
  128. json = r.json()
  129. except requests.exceptions.Timeout:
  130. print("Connection Timed out!")
  131. except requests.exceptions.TooManyRedirects:
  132. print("Too Many redirects")
  133. except requests.exceptions.RequestException as e:
  134. print("Unable to access the Url. \nPlease ensure you are connected to vpn!\n")
  135. logfile.write(("Error reported: %s" %e).encode())
  136. sys.exit(1)
  137. json = r.json()
  138. try:
  139. results_cert = json[0]['results']
  140. headings_cert = json[0]['headings']
  141. except KeyError:
  142. print("Error encountered with CERT Appliance: %s" %json['message'])
  143.  
  144.  
  145.  
  146. # load input to intermediate output file
  147. ofile = open(TEMP_FILE, "a")
  148. try:
  149. if len(results_cert) != 0:
  150. check_EMPTY_CERT = False
  151. ofile.write('*Data from CERT* \n')
  152. ofile.write(','.join(headings_cert))
  153. ofile.write('\n')
  154. for item in results_cert:
  155. ofile.write(",".join(map(str, item)))
  156. ofile.write('\n')
  157.  
  158. else:
  159. check_EMPTY_CERT = True
  160. print("Error:No Data found in CERT")
  161. logfile.write("Error:No Data found in CERT \n".encode())
  162. except NameError:
  163. pass
  164. ofile.close()
  165.  
  166.  
  167. # Data Formatting
  168. ifile = open(TEMP_FILE, "r")
  169. reader = csv.reader(ifile)
  170. ofile = open(JIRA_OUTPUT_FILE, "w")
  171. writer = csv.writer(ofile, delimiter='|', lineterminator='|\n |', quoting=csv.QUOTE_NONE, escapechar=' ')
  172. for row in reader:
  173. writer.writerow(row)
  174. ofile.close()
  175. ifile.close()
  176.  
  177. #Option to add extra comment
  178. option = input("\nTo add extra comments. Press 1 else 0: \n")
  179. comment_check = option
  180. while (option == '1'):
  181. ofile = open(JIRA_OUTPUT_FILE, "a")
  182. Extra_comment = input("Enter the comment below: \n")
  183. ofile.write("\n %s" % Extra_comment)
  184. option = input("To continue adding comment, Press 1 else 0:\n")
  185. ofile.close()
  186.  
  187.  
  188.  
  189. #Check if Output file is empty, if not add comment to jira
  190. if ( check_EMPTY_PROD and check_EMPTY_CERT and comment_check == '0'):
  191. print("Error:No Data found in Prod and Cert and No comments added. Exiting...")
  192. logfile.write("Error:No Data found in Prod and Cert. No comments added. Exiting... \n".encode())
  193. exit(1)
  194. else:
  195. Jira_output = open(JIRA_OUTPUT_FILE, "r")
  196. Jira_Comment = Jira_output.read()
  197. print("\nBelow data will be posted to Jira as comment. Please ignore trailing '|' character: \n \n%s \n \n" % Jira_Comment)
  198. print("++++++++++++++++++++++++++++++++++++++")
  199. print("To post the comment to Jira, please provide your Credentials.\n ")
  200.  
  201. # Accept Username and password required for Jira authentication from the user
  202. username = input("Enter your Jira LoginUser: \n ")
  203. if sys.stdin.isatty():
  204. p = getpass.getpass('Password: ')
  205. else:
  206. print('Password:')
  207. p = sys.stdin.readline().rstrip()
  208.  
  209. # Connect to jira and add comment
  210. jira = JIRA('https://jira3.cerner.com/')
  211. issue = jira.issue(config.Issue_id)
  212. options = {
  213. 'server': 'https://jira3.cerner.com/'
  214. }
  215. try:
  216. jira = JIRA(basic_auth=(username, p), options=options)
  217. except JIRAError as e:
  218. if e.status_code == 401:
  219. print("Login to JIRA failed. Check your username and password")
  220. logfile.write("Login to JIRA failed. Check your username and password \n".encode())
  221. exit(1)
  222. else:
  223. print("Something wrong! ")
  224. logfile.write(("Error: %s" % e.status_code).encode())
  225. exit(1)
  226.  
  227. jira.add_comment(issue, ' %s ' % Jira_Comment)
  228. print("Success:Comment added to jira with the Maintenance data")
  229. logfile.write("Success:Comment added to jira with the Maintenance data \n".encode())
Add Comment
Please, Sign In to add comment