## Provide download location ## If "", files will be created where this script located ## Use forward slash to show path. ## Always end with a slash. Eg: "D:/temp/", "/home/user/Downloads/" DOWNLOAD_LOCATION = "D:/temp/" ## ************************ ## CONFIGURATIONS End ## ************************ if not os.path.exists(DOWNLOAD_LOCATION): os.makedirs(DOWNLOAD_LOCATION) options = {'server': JIRA_SERVER, 'basic_auth': (JIRA_USERNAME, JIRA_PASSWORD)} jira_inst = JIRA(**options) def init_logging(): '''function to initialize logging''' log_filename = "log_" + str(datetime.now()).split(".")[0].replace( ":", "") + ".txt" logging.basicConfig(filename=DOWNLOAD_LOCATION + log_filename, level=logging.INFO, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p') def download_file(url_data): '''function to download the file from given url''' local_filename = url_data[0]
def get_jira_client(): jira_credentials = __get_credentials() jira_options = {'server':jira_credentials.get('server', '')} jira_client = JIRA(options=jira_options, basic_auth=(jira_credentials.get('userName', ''),jira_credentials.get('password', ''))) return jira_client
import commands import logging import click import os from jira import JIRA import tabulate logger = logging.getLogger(__name__) DEFAULT_JIRA_URL = "https://jira.atlassian.com" jira = JIRA(os.environ.get('JIRA_URL', DEFAULT_JIRA_URL), basic_auth=(os.environ.get('JIRA_USERNAME'), os.environ.get('JIRA_TOKEN'))) def tmux(command): status, output = commands.getstatusoutput('tmux {}'.format(command)) logger.debug('tmux command status: {}'.format(status)) return output def current_session(): return tmux('display-message -p "#S"') def get_sessions(): return [session.split(':')[0] for session in tmux('ls').split('\n')]
import datetime import sys import webbrowser from getpass import getpass from loguru import logger from jira import JIRA, JIRAError @logger.catch def createhtml(htmlbody): """ Create an HTML page to cut & paste into email """ logger.info("Generating HTML") file = open('output.html', 'w') file.write(BODY) file.close webbrowser.open('output.html') if __name__ == "__main__": #USERNAME = os.getlogin() BODY = '' SERVER = 'https://jira.starrez.com' USERNAME = '******' print("JIRA Username: "******"JIRA Password: "******"Error", error.status_code, "-", error.text) sys.exit(1)
''' Searches for specific labels and replaces them cleanup script, ie aisEAI vs aisEai based on https://jira.readthedocs.io/ credentials are saved in a separate file credentials.py, ie: username = "******" password = "******" ''' import sys, re, credentials from jira import JIRA jira = JIRA(server="https://srfmmz.atlassian.net", basic_auth=(credentials.username, credentials.password)) label_to_replace = "aisEai" label_replacement = "aisEAI" page = 0 while(1): print("page {page}".format(page=page)) stories = jira.search_issues('project in (AIS, AISK) and labels in ({label})'.format(label=label_to_replace), startAt=page, maxResults=100, fields='labels') #stories = [jira.issue("AIS-19280")] if (len(stories) == 0): break page += 100 for story in stories: if (label_to_replace in story.fields.labels): labels = story.fields.labels print("updating {id}: {labels}".format(id=story.key, labels=labels)) labels.remove(label_to_replace)
for Marker in Markers: Output += generate_Code_Text(Marker, sourcecode) return Output ##### MAIN ##### log_msg("**** Suggestion to Jira ****") if not (len(sys.argv) == 2): log_error("Need filename as argument") sys.exit(1) log_msg("Connecting to Jira") try: jira = JIRA(config.Jira['host'], basic_auth=(config.Jira['user'], config.Jira['token'])) except: log_error("Problems with JIRA") sys.exit(1) # Clean up before log_msg("Cleaning temp directory") repo_path = pathlib.Path(config.Git['repo_dir']) if repo_path.exists: os.system("rd /s /Q {dir}".format(dir=pathlib.PureWindowsPath(repo_path))) # - get checks from DC in log_msg("Loading Suggestion JSON") #dc_suggestions = load_demo_json() dc_suggestions = load_json(sys.argv[1])
#!/usr/bin/env python import yaml import os from time import strftime from jira import JIRA Yaml = 'svnConf.yml' with open(Yaml,'r') as yamlFile: conf = yaml.load(yamlFile) address = conf['address'] Jira = conf['jira'] log = address['dest'] + 'logs/' + strftime("%Y%m%d-%H%M") + '.rsync.log' jiraServer = JIRA(options={'server':Jira['addr'],'verify':False},basic_auth=(Jira['user'],Jira['pass'])) def sendJira(desc): jiraServer.create_issue(project=Jira['project'],summary=Jira['summary'],description=desc,issuetype={'name':'Bug'},assignee={'name':Jira['assign']}) if not os.path.exists(log): sendJira(Jira['desc']) elif (os.path.getsize(conf['err']) > 0 ): with open(conf['err'],'r') as errors: desc = errors.read() sendJira(desc) else: print('safe')
def get_jira_client(domain, username, password): options = {'server': domain} return JIRA(options, basic_auth=(username, password))
def __init__(self, jira_config): self.client = JIRA(jira_config.address, basic_auth=(jira_config.basic_auth_user, jira_config.basic_auth_pass))
def conn(self): jira=JIRA(server=self.server,basic_auth=self.basic_auth) return jira
# from jira import JIRA from jira.client import GreenHopper from DataHandler import jira_class_epic import sys """设置字符集 """ reload(sys) sys.setdefaultencoding('utf-8') options = { 'server': 'http://jira.chinacloud.com.cn', } jira = JIRA('http://jira.chinacloud.com.cn', basic_auth=('shenwei', 'sw64419')) gh = GreenHopper(options, basic_auth=('shenwei', 'sw64419')) def main(): project_list = jira.projects() for _p in project_list: try: print(u">>> [%s] ... ing" % _p) my_jira = jira_class_epic.jira_handler(_p.key) _sprints = my_jira.get_sprints() jira_class_epic.do_with_epic(my_jira, _sprints) jira_class_epic.do_with_task(my_jira) print(u">>> .ed.") except Exception, e:
from django.http import JsonResponse from django.core.mail import BadHeaderError, send_mail from datetime import date, timedelta import json from django.conf import settings from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from django.core import serializers from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import generics from jira import JIRA auth_jira = JIRA('https://cogniable.atlassian.net', basic_auth=('*****@*****.**', 'QbvAH5jVtFrMykcKfgq8A81E')) class CreateTicket(APIView): authentication_classes = (JWTAuthentication, ) permission_classes = (IsAuthenticated, ) serializer_class = TicketsSerializer def get(self, request, format=None): ticket_obj = Tickets.objects.all() serializer = self.serializer_class(ticket_obj, many=True) res_dict = {} res_dict['status'] = 1 res_dict['detail'] = "tickets Api"
def create_jira_authentication(self): jira = JIRA(ATLASSIAN_URL, basic_auth=(USER_NAME, API_TOKEN)) return jira
# Developed by Koushik - Apr 2020 # Purpose: Search for issues in current sprint from jira import JIRA import getpass # login to JIRA using username and password print ("Enter credentials to login to JIRA:") user = input("Username: ") pw = getpass.getpass() jira = JIRA(auth=(user, pw) , options = {'server': 'https://jira.kfplc.com'}) # get active sprint issues in a Project - ignore 'and status != Done' #issues_in_proj = jira.search_issues('project=DRRR') issues_in_project = jira.search_issues('project=DRRR and sprint not in closedSprints() AND sprint not in futureSprints() ') print ('-------- All issues in current sprint -------') for value in issues_in_project: print(value.key, ':', value.fields.summary, ':(',value.fields.assignee, ')') # Summaries of my last 3 reported issues print ('------ Summary of my last 3 reported issues --------') for issue in jira.search_issues('reporter = currentUser() order by created desc', maxResults=3): print('{}: {}'.format(issue.key, issue.fields.summary)) # To be tested print ('------ Count of open issues in active sprint ------- ') openIssues = jira.search_issues('project=DRRR and sprint not in closedSprints() AND sprint not in futureSprints() AND status != Done', startAt=0, maxResults=0,
def jira(self): return JIRA(options=dict(server=self.server, verify=False), basic_auth=(self.username, self.password))
def __init__(self, url, login, password) -> None: self.jira = JIRA(url, auth=(login, password))
from jira import JIRA options = {"server": "https://jira.banvien.com.vn"} user = "******" #your username log in JIRA pw = "Pass1234" #your password log in JIRA jira = JIRA(options, basic_auth=(user, pw)) #issues = dict() issues = jira.search_issues( "issue='MUT-830' or (assignee=currentUser() and status!=done)") #print (issues) print "You have a total", len(issues), "tasks." for i in range(0, len(issues)): #print (issues[i]) pos = i print "Task", pos + 1, ":", issues[i], ":", issues[i].fields.summary #print (" -> Name: ",issues[i].fields.summary) #print (" Status: ",issues[i].fields.status) print("==================================================") while 1: value = raw_input("You choose task number ? ") ID_JIRA = issues[int(value) - 1] print "=== ", issues[int(value) - 1].fields.summary, " ===" time = raw_input("Spent time (5h, 30m...): ") com = raw_input("Comment: ") print "You want to log work on: " print " 1. Today" print " 2. Other date" choice = raw_input("You choose 1 or 2 ? ") if int(choice) == 2:
cur_date = d.datetime.now().strftime('%Y-%m-%d %H:%M:%S') conn = psycopg2.connect("dbname=Jiradb user=postgres password=1 port=5433") cur = conn.cursor() print('Program started. (' + cur_date + ')') user_name = 'user.name' password = '******' mail_password = '******' train = [] start_time = time.time() # Jira Server Connection options = {'server': 'http://your.domain.com'} # Authentication try: jira = JIRA(options, basic_auth=(f'{user_name}', f'{password}')) except BaseException as Be: print(Be) props = jira.application_properties() # JQL for all closed issues # All closed issues of the last month all_closed_issues = jira.search_issues( ‘resolution in (Resolved, Cancelled, Repeated ,”Not Repeatable”) and assignee is not EMPTY order by createdDate asc’, maxResults=False) ) i = 0 for i in range(0, len(all_closed_issues)):
f = open(ConfigFile, "r") #---- DeviceTest = f.read() #------ postString = DeviceTest.split("\n", 1)[1] #No Config Now print(postString) preconfig = '==========>Device Test Information<============' + '\n' preconfig += postString preconfig += '\n' preconfig += '\n' result = ParserRobotXML(xmlPath) testCaseFail = result.getFailCases() print(testCaseFail.count) jira = JIRA(server=HOST, basic_auth=(UserName, Token)) for tc in testCaseFail: new_issue = jira.create_issue(project='MST', summary='[' + DeviceName + ']' + tc.testName, description=preconfig + tc.getStringTestCase(), issuetype={'name': 'Bug'}) fileName = tc.captureScreen #---- if fileName != "": path = ReportPath + fileName print(path) # jira.add_attachment(issue=new_issue, attachment=path) with open(path, 'rb') as f: jira.add_attachment(issue=new_issue, attachment=f)
def update_tickets_from_git(last=None, current=None): """ Run during a deployment. Looks at all commits between now and the last deployment. Finds all ticket numbers and updates their status in Jira. """ from jira import JIRA, JIRAError from burlap.deploy import get_last_current_diffs from burlap.git import gittracker get_current_commit = gittracker.get_current_commit GITTRACKER = gittracker.name.upper() dryrun = common.get_dryrun() verbose = common.get_verbose() # Ensure this is only run once per role. if env.host_string != env.hosts[-1]: return if not env.jira_update_from_git: return if not env.jira_ticket_pattern: return if not env.jira_basic_auth_username or not env.jira_basic_auth_password: return # During a deployment, we should be given these, but for testing, # lookup the diffs dynamically. if not last or not current: last, current = get_last_current_diffs(GITTRACKER) if verbose: print('-' * 80) print('last.keys:', last.keys()) print('-' * 80) print('current.keys:', current.keys()) try: last_commit = last['GITTRACKER']['current_commit'] except KeyError: return current_commit = current['GITTRACKER']['current_commit'] # Find all tickets deployed between last deployment and now. tickets = get_tickets_between_commits(current_commit, last_commit) if verbose: print('tickets:', tickets) # Update all tickets in Jira. jira = JIRA({'server': env.jira_server}, basic_auth=(env.jira_basic_auth_username, env.jira_basic_auth_password)) for ticket in tickets: # Mention this Jira updated. comment = env.jira_ticket_update_message_template % dict( role=env.ROLE.lower()) print('Commenting on ticket %s: %s' % (ticket, comment)) if not dryrun: jira.add_comment(ticket, comment) # Update ticket status. recheck = False while 1: print('Looking up jira ticket %s...' % ticket) issue = jira.issue(ticket) print('Ticket %s retrieved.' % ticket) transition_to_id = dict( (t['name'], t['id']) for t in jira.transitions(issue)) print('%i allowable transitions found: %s' % (len(transition_to_id), ', '.join(transition_to_id.keys()))) next_transition_name = env.jira_deploy_workflow.get( issue.fields.status.name.title()) next_transition_id = transition_to_id.get(next_transition_name) if next_transition_name: new_fields = {} # print('jira_assignee_by_status:', env.jira_assignee_by_status, issue.fields.status.name.title() new_assignee = env.jira_assignee_by_status.get( #issue.fields.status.name.title(), next_transition_name, issue.fields.assignee.name, ) if new_assignee == 'reporter': new_assignee = issue.fields.reporter.name # print('new_assignee:', new_assignee) print('Updating ticket %s to status %s and assigning it to %s.' \ % (ticket, next_transition_name, new_assignee)) if not dryrun: try: jira.transition_issue( issue, next_transition_id, ) recheck = True except AttributeError as e: print('Unable to transition ticket %s to %s: %s' \ % (ticket, next_transition_name, e), file=sys.stderr) # Note assignment should happen after transition, since the assignment may # effect remove transitions that we need. try: if new_assignee: print('Assigning ticket %s to %s.' % (ticket, new_assignee)) jira.assign_issue(issue, new_assignee) else: print('No new assignee found.') except JIRAError as e: print('Unable to reassign ticket %s to %s: %s' \ % (ticket, new_assignee, e), file=sys.stderr) else: recheck = False print('No transitions found for ticket %s currently in status "%s".' \ % (ticket, issue.fields.status.name)) if not recheck: break
def _get_jira(server: str, username: str, password: str) -> JIRA: return JIRA(server=server, basic_auth=(username, password), max_retries=1)
cmd1 = "avocado list {}".format(_file) output = subprocess.check_output(cmd1, shell=True) tests += len(output.splitlines()) yamlfile = yamlforpy(_file) cmd2 = ( "avocado variants -m {} --summary 0 --variants 1".format(yamlfile)) output = subprocess.check_output(cmd2, shell=True) variants += len(output.splitlines()) print(".") sys.stdout.flush() print("existing avocado tests> {}".format(tests)) print("existing avocado variants> {}".format(variants)) options = {'server': 'https://jira.hpdd.intel.com'} jira = JIRA(options) issues = jira.search_issues('project=DAOS AND component=test AND ' 'assignee=daos-triage') print("test stories in backlog> {}".format(issues.total)) q = """project=DAOS AND component=test AND project=DAOS AND status in ("In Progress","In Review")""" issues = jira.search_issues(q) print("total test stories in progress> {}".format(issues.total)) q = """project=DAOS AND component=test AND project=DAOS AND status in ("Closed","Done","Resolved")""" issues = jira.search_issues(q) print("total test stories completed> {}".format(issues.total))
def lambda_handler(event, context): # boto3 clients ssm = boto3.client('ssm') securityhub = boto3.client('securityhub') # create env vars lambdaFunctionName = os.environ['AWS_LAMBDA_FUNCTION_NAME'] # JIRA specific variables jiraUrl = os.environ['JIRA_URL'] jiraIssueCreatorUsername = os.environ['JIRA_ISSUE_CREATOR_USERNAME'] jiraApiKeySSMParam = os.environ['JIRA_APIKEY_SSM_PARAM'] jiraProjectKey = os.environ['JIRA_PROJECT_KEY'] # decrypt & get API key from SSM response = ssm.get_parameter(Name=jiraApiKeySSMParam, WithDecryption=True) jiraApiKey = str(response['Parameter']['Value']) # JIRA project AuthN options = {'server': jiraUrl} jira = JIRA(options, auth=(jiraIssueCreatorUsername, jiraApiKey)) # parse ASFF securityHubEvent = (event['detail']['findings']) for findings in securityHubEvent: # parse finding details findingSeverity = str( findings['ProductFields']['aws/securityhub/SeverityLabel']) if findingSeverity == 'CRITICAL': jiraPriority = str('Highest') elif findingSeverity == 'HIGH': jiraPriority = str('High') elif findingSeverity == 'MEDIUM': jiraPriority = str('Medium') elif findingSeverity == 'LOW': jiraPriority = str('Low') elif findingSeverity == 'INFORMATIONAL': jiraPriority = str('Lowest') else: return 1 findingId = str(findings['Id']) findingOwner = str(findings['AwsAccountId']) findingTitle = str(findings['Title']) findingDesc = str(findings['Description']) for resources in findings['Resources']: resourceId = str(resources['Id']) new_issue = jira.create_issue( project=jiraProjectKey, summary=resourceId + ' has failed ' + findingTitle, description=resourceId + ' in account ' + findingOwner + ' has failed check ' + findingTitle + ' Security Hub description includes the following information: ' + findingDesc, issuetype={'name': 'Bug'}, priority={'name': jiraPriority}) jiraIssueId = str(new_issue) try: response = securityhub.update_findings( Filters={ 'Id': [{ 'Value': findingId, 'Comparison': 'EQUALS' }] }, Note={ 'Text': 'The finding was either kept ACTIVE or moved back to an ACTIVE state. This finding has been created in the JIRA project ' + jiraProjectKey + ' as Issue ID ' + jiraIssueId, 'UpdatedBy': lambdaFunctionName }, RecordState='ACTIVE') print(response) except Exception as e: print(e)
def getContent(self): return JIRA(self.server, basic_auth=(self.email, self.pwd))
# 3 weeks before from current date #Date4 = os.popen("date +%Y/%m/%d -d '-22 dayes'") #week_before3 = Date3.read() # Describe mail details sender = '*****@*****.**' receiver = ['*****@*****.**'] #CC = ['*****@*****.**','*****@*****.**'] msg = MIMEMultipart('alternative') msg['Subject'] = "Blocked Tickets" msg['From'] = sender msg['To'] = ", ".join(receiver) # authendicating jira with username & password options = {'server': 'https://bits.bazaarvoice.com/jira'} jira = JIRA(options, basic_auth=('', '')) # DOS touched blocked tickets blocked_issues_for_1week = jira.search_issues( "labels = DOSTeam AND status = Blocked AND updated < '-7d' ORDER BY updated DESC", maxResults=5000) blocked_issues_for_2week = jira.search_issues( "labels = DOSTeam AND status = Blocked AND updated < '-14d' ORDER BY updated DESC", maxResults=5000) blocked_issues_for_3week = jira.search_issues( "labels = DOSTeam AND status = Blocked AND updated < '-21d' ORDER BY updated DESC", maxResults=5000) blocked_issues_for_4weekandmore = jira.search_issues( "labels = DOSTeam AND status = Blocked AND updated < '-28d' ORDER BY updated DESC", maxResults=5000)
from collections import defaultdict from typing import List from jira import Issue from jira import JIRA import argparse from gantt_chart import GanttChart from issue_graph import IssueGraph username = os.environ.get('JIRA_USERNAME') token = os.environ.get('JIRA_TOKEN') options = {'server': os.environ.get('JIRA_HOST')} cookie = (username, token) auth_jira = JIRA(options, basic_auth=cookie) parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--epics', type=str, nargs='+', default=[]) parser.add_argument('--sprints', type=str, nargs='+', default=[]) parser.add_argument('--releases', type=str, nargs='+', default=[]) parser.add_argument('--show_gantt', action='store_true', default=False) parser.add_argument('--show_graph', action='store_true', default=False) args = parser.parse_args() filters = [] if args.epics: filters.append(' OR '.join(f'"Epic Link"={epic_key}' for epic_key in args.epics)) if args.sprints: filters.append(' OR '.join(f'"Sprint"="{sprint_key}"'
# This script shows how to use the client in anonymous mode # against jira.atlassian.com. import re from jira import JIRA # By default, the client will connect to a Jira instance started from the Atlassian Plugin SDK # (see https://developer.atlassian.com/display/DOCS/Installing+the+Atlassian+Plugin+SDK for details). jira = JIRA(server="https://jira.atlassian.com") # Get all projects viewable by anonymous users. projects = jira.projects() # Sort available project keys, then return the second, third, and fourth keys. keys = sorted(project.key for project in projects)[2:5] # Get an issue. issue = jira.issue("JRA-1330") # Find all comments made by Atlassians on this issue. atl_comments = [ comment for comment in issue.fields.comment.comments if re.search(r"@atlassian.com$", comment.author.key) ] # Add a comment to the issue. jira.add_comment(issue, "Comment text") # Change the issue's summary and description. issue.update( summary="I'm different!", description="Changed the summary to be different."
def get_sites_deployed_in_QA_2018() -> list: jira = JIRA(settings.JIRA_URL, basic_auth=(settings.JIRA_USERNAME, settings.JIRA_PASSWORD)) sites = jira.search_issues('project = WP2018 AND status = "Copié en QA18 à notifier" AND cf[10903] != "Conf. Sub domain" AND cf[10903] != "Lab ventilé"', maxResults=10000) return sites
with open(commandExecutionExceptions.ignore, mode='r',newline='') as csv_file: for line in csv_file: logging.info(line.replace('\n', ' ').replace('\r', '')) ignoreList.append(line.replace('\n', '').replace('\r', '')) if commandExecutionExceptions.export != None: fileExport = open(commandExecutionExceptions.export,"w") f = Figlet(font='slant') print (f.renderText('Your Xray test execution definition synchronizer!')) #Get auth token and build header for requests response = requests.post('https://xray.cloud.xpand-it.com/api/v1/authenticate', data={"client_id": GLOBAL_client_id,"client_secret":GLOBAL_client_secret}) token=response.text.replace("\"","") headers = {'Authorization':'Bearer %s' % token} jira = JIRA(basic_auth=(GLOBAL_basic_auth_user, GLOBAL_basic_auth_pass),options={"server": GLOBAL_onPremiseURL}) # a username/password tuple jiraCloud = JIRA(basic_auth=(GLOBAL_cloudUser, GLOBAL_apitoken),options={"server": GLOBAL_onCloudMig}) # a username/password tuple # Get all Tests logging.info("-------") logging.info("======= Collecting INFO [START] =========") logging.info("Processing Tests...") block_size = 100 block_num = 0 mutation = "" issuesScanned = [] keyStats = [] timeStats = [] hasPushStats = []
iftt_url = os.environ["iftt_url"] jira_username = os.environ["jira_username"] jira_password = os.environ["jira_password"] jira_url = os.environ["jira_url"] jira_search = os.environ["jira_search"] ping_duration_seconds = int(os.environ["ping_duration_seconds"]) def send_notification(text): """Send Notification via IFTTT webhook""" result = requests.post(iftt_url, data={'value1': text}) result.raise_for_status() print(text) client = JIRA(jira_url, auth=(jira_username, jira_password)) while True: interesting_issues = client.search_issues(jira_search) for issue in interesting_issues: if issue.key in seen_issues: continue seen_issues.append(issue.key) MSG = None if issue.fields.assignee is None: MSG = "[%s Unassigned] %s" % (issue.key, issue.fields.summary) else: MSG = "[%s %s] %s" % (issue.key, issue.fields.assignee.displayName, issue.fields.summary)