Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- from jira import JIRA
- from datetime import datetime, timedelta
- import csv
- import getpass
- import sys
- import config
- from jira.exceptions import JIRAError
- #Processing files
- TEMP_FILE = "output.txt"
- JIRA_OUTPUT_FILE="Jira_output.txt"
- Jira_log = "Jira_log.txt"
- out_file = open(TEMP_FILE,"w")
- out_file.write("|")
- with open( Jira_log, "wb") as logfile:
- # Adjust the date
- scandate = datetime.today() - timedelta(days=config.n)
- scandate = str(scandate.date())
- logfile.write(("Scandate is taken as %s \n" % scandate).encode())
- #Fetch and process data for Prod
- # Arg_prod
- length_prod = len(config.Keywordlist_Prod)
- #Add conditional statement
- if (length_prod == 0):
- print("No scan Arguments provided in config.py for PROD")
- check_EMPTY_PROD = True
- logfile.write("No scan Arguments provided in config.py for PROD \n".encode())
- else:
- arg_prod = ""
- for i in range(0, length_prod - 1):
- arg_prod = arg_prod + config.Keywordlist_Prod[i] + "|"
- arg_prod = arg_prod + config.Keywordlist_Prod[(length_prod - 1)]
- logfile.write("Fetching results from PROD....\n".encode())
- # Url for ADDM Appliance
- url = config.url_prod
- # Add API TOKEN in headers
- headers = {
- 'Accept': 'application/json' ,
- 'Authorization': 'Bearer Mzo1M2U1ZTAzNWRkZWRiZGRlMDg0NjA3MjgwMWNjMWQzZjphcGlfdXNlcjowLTIwZWM2NDQyMDU4YWNmZDc4ZjRiMDI3ZWUwNjBmZmYwZTgxZjVmODFjYjk3ZmU4Y2IxZDAwNmQ5MjkwZTY4Yzk='
- }
- # Search query for fetching data
- params = {
- '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,
- 'limit': 1000
- }
- print("Fetching Data from PROD. Please wait....! ")
- try:
- r = requests.get(url=url, params=params, headers=headers)
- except requests.exceptions.Timeout:
- print("Connection Timed out!")
- except requests.exceptions.TooManyRedirects:
- print("Too Many redirects")
- except requests.exceptions.RequestException as e:
- print("Unable to access the Url. \nPlease ensure you are connected to vpn!\n")
- logfile.write(("Error reported: %s" %e).encode())
- sys.exit(1)
- #Response recived in json format
- json = r.json()
- results_prod = json[0]['results']
- headings_prod = json [0]['headings']
- # load data to intermediate output file
- ##out_file = open(TEMP_FILE,"w")
- if len(results_prod) != 0:
- check_EMPTY_PROD = False
- out_file.write("*Data from PROD* \n")
- out_file.write(','.join(headings_prod))
- out_file.write('\n')
- for item in results_prod:
- out_file.write(",".join(map(str, item)))
- out_file.write('\n')
- else:
- check_EMPTY_PROD = True
- print("Error:No Data found in PROD")
- logfile.write("Error:No Data found in PROD \n".encode())
- out_file.close()
- #Fetch and process data for CERT
- # Arg_cert
- length_cert = len(config.Keywordlist_Cert)
- if (length_cert == 0):
- print("No scan Arguments provided in config.py for CERT")
- check_EMPTY_CERT = True
- logfile.write("No scan Arguments provided in config.py for CERT \n".encode())
- else:
- arg_cert = ""
- for i in range(0, length_cert - 1):
- arg_cert = arg_cert + config.Keywordlist_Cert[i] + '|'
- arg_cert = arg_cert + config.Keywordlist_Cert[(length_cert - 1)]
- logfile.write("Fetching results from CERT....\n".encode())
- #Url for ADDM Appliance
- url = config.url_cert
- #Add API TOKEN in headers
- headers = {
- 'Accept': 'application/json',
- 'Authorization': 'Bearer MzoyYzY3Y2QzNWRkZTUyZWYxMWFkODA3MjgwM2Q3MDdkZDphcGlfdXNlcjowLTRiZDcyYjNmMDhjNzA1NjgwOGUwMTlhMDJmYzhhNTY2M2U2ZDU2ODE0YTEzODEzMWQzNTA3MmQzYTliYjc4ZTQ='
- }
- #Search query for fetching data
- params = {
- '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 ,
- 'limit': 1000
- }
- print("Fetching data from CERT. Please wait....!")
- try:
- r = requests.get(url=url, params=params, headers=headers)
- json = r.json()
- except requests.exceptions.Timeout:
- print("Connection Timed out!")
- except requests.exceptions.TooManyRedirects:
- print("Too Many redirects")
- except requests.exceptions.RequestException as e:
- print("Unable to access the Url. \nPlease ensure you are connected to vpn!\n")
- logfile.write(("Error reported: %s" %e).encode())
- sys.exit(1)
- json = r.json()
- try:
- results_cert = json[0]['results']
- headings_cert = json[0]['headings']
- except KeyError:
- print("Error encountered with CERT Appliance: %s" %json['message'])
- # load input to intermediate output file
- ofile = open(TEMP_FILE, "a")
- try:
- if len(results_cert) != 0:
- check_EMPTY_CERT = False
- ofile.write('*Data from CERT* \n')
- ofile.write(','.join(headings_cert))
- ofile.write('\n')
- for item in results_cert:
- ofile.write(",".join(map(str, item)))
- ofile.write('\n')
- else:
- check_EMPTY_CERT = True
- print("Error:No Data found in CERT")
- logfile.write("Error:No Data found in CERT \n".encode())
- except NameError:
- pass
- ofile.close()
- # Data Formatting
- ifile = open(TEMP_FILE, "r")
- reader = csv.reader(ifile)
- ofile = open(JIRA_OUTPUT_FILE, "w")
- writer = csv.writer(ofile, delimiter='|', lineterminator='|\n |', quoting=csv.QUOTE_NONE, escapechar=' ')
- for row in reader:
- writer.writerow(row)
- ofile.close()
- ifile.close()
- #Option to add extra comment
- option = input("\nTo add extra comments. Press 1 else 0: \n")
- comment_check = option
- while (option == '1'):
- ofile = open(JIRA_OUTPUT_FILE, "a")
- Extra_comment = input("Enter the comment below: \n")
- ofile.write("\n %s" % Extra_comment)
- option = input("To continue adding comment, Press 1 else 0:\n")
- ofile.close()
- #Check if Output file is empty, if not add comment to jira
- if ( check_EMPTY_PROD and check_EMPTY_CERT and comment_check == '0'):
- print("Error:No Data found in Prod and Cert and No comments added. Exiting...")
- logfile.write("Error:No Data found in Prod and Cert. No comments added. Exiting... \n".encode())
- exit(1)
- else:
- Jira_output = open(JIRA_OUTPUT_FILE, "r")
- Jira_Comment = Jira_output.read()
- print("\nBelow data will be posted to Jira as comment. Please ignore trailing '|' character: \n \n%s \n \n" % Jira_Comment)
- print("++++++++++++++++++++++++++++++++++++++")
- print("To post the comment to Jira, please provide your Credentials.\n ")
- # Accept Username and password required for Jira authentication from the user
- username = input("Enter your Jira LoginUser: \n ")
- if sys.stdin.isatty():
- p = getpass.getpass('Password: ')
- else:
- print('Password:')
- p = sys.stdin.readline().rstrip()
- # Connect to jira and add comment
- jira = JIRA('https://jira3.cerner.com/')
- issue = jira.issue(config.Issue_id)
- options = {
- 'server': 'https://jira3.cerner.com/'
- }
- try:
- jira = JIRA(basic_auth=(username, p), options=options)
- except JIRAError as e:
- if e.status_code == 401:
- print("Login to JIRA failed. Check your username and password")
- logfile.write("Login to JIRA failed. Check your username and password \n".encode())
- exit(1)
- else:
- print("Something wrong! ")
- logfile.write(("Error: %s" % e.status_code).encode())
- exit(1)
- jira.add_comment(issue, ' %s ' % Jira_Comment)
- print("Success:Comment added to jira with the Maintenance data")
- logfile.write("Success:Comment added to jira with the Maintenance data \n".encode())
Add Comment
Please, Sign In to add comment