def __init__(self, job_name, chose='jenkins'): self.job_name = job_name config = get_jk_config(chose) self.jk = Jenkins(*config, useCrumb=True)
def test_jenkins(): jenkins = Jenkins('http://localhost:8080/jenkins/', username="******", password="") print(jenkins.keys())
def __init__(self, jenkins_url="http://localhost:8080", name="name", key="key"): self.server = Jenkins(jenkins_url, name, key)
app = Flask(__name__) api = Api(app) db = SQLAlchemy(app) username = '******' password = '******' host = '127.0.0.1' port = 3306 dbname = 'flask' option = 'charset=utf8mb4' app.config[ 'SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?{option}' jenkins = Jenkins('http://shifeng.online:8080/', username='******', password='******') jenkins_job = jenkins['jenkinsapi_test'] class TestCase(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True, nullable=False) description = db.Column(db.String(120), unique=False, nullable=False) testcases = db.Column(db.String(1024), nullable=True) def __repr__(self): return '<User %r>' % self.id def as_dic(self): return {
def setUp(self): self.jenkins = Jenkins("http://localhost:8080") self.plugins = self.jenkins.get_plugins()
def get_server_instance(): """ Get jenkins server instance """ server = Jenkins(URL, username=USERNAME, password=PASSWORD) return server
def __init__(self, url, user, passwd, job_name): self.jenkins = Jenkins(url, user, passwd) self.job_name = job_name self._job = self.jenkins.get_job(job_name)
def __init__(self): jenkins_server = 'http://192.168.6.11:8080' self._jenkins_conn = Jenkins(baseurl=jenkins_server, username='******', password='******', timeout=1000)
# #header # req.add_header("Authorization","Basic emhhbmdzaGVuZzoxMjM0NQ==") # req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) # req.add_header('User-Agent','Mozilla/5.0') # #post data to server # resp = urllib2.urlopen(req, timeout=5) # # #get response # qrcont=resp.read() # print qrcont # except Exception,e: # print e # # uploadConfigFile(); jenkinsSource = 'http://172.16.100.150:8085/' server = Jenkins(jenkinsSource, username = '******', password = '******') myJob=server.get_job("bjmcManagerFE_beta") keys = server.keys(); # print keys #print server['bjmcManagerFE_beta'] myConfig=myJob.get_config() # print myConfig new = myConfig.replace('<string>clean</string>', '<string>string bean</string>') f = open('config-old.xml','r') cc = f.read() nnn = re.sub(r"<stableText>.*</stableText>","<stableText>ggg</stableText>",cc) # with open("config-new.xml", "wb+") as code: # code.write(nnn) myJob.update_config(nnn)
import jenkinsapi from jenkinsapi.jenkins import Jenkins import sqlite3 import getpass import time import datetime username = raw_input("Username: "******"Password: "******"Error logging in") db = sqlite3.connect('jenkinsdb') cursor = db.cursor() null = "NULL" #Jobs don't have to have a description, this will be used in such cases jobs = [] cursor.execute( 'CREATE table IF NOT exists Jobs (name TEXT, description TEXT, lastBuild INTEGER, buildStatus TEXT, dateChecked TEXT)' ) print "Getting jobs..." for job_name, job_instance in J.get_jobs(): if not job_instance.is_queued_or_running(): print "Getting information on job " + job_name last_build = job_instance.get_last_build() last_build_status = last_build.get_status() if job_instance.get_description() is None:
build_result['error'] = error_list return build_result # parse command line argp = argparse.ArgumentParser(description='Get build statistics.') argp.add_argument('-u', '--username', default='jenkins') argp.add_argument('-b', '--builds', choices=['all'] + sorted(_BUILDS.keys()), nargs='+', default=['all']) args = argp.parse_args() J = Jenkins('https://grpc-testing.appspot.com', args.username, 'apiToken') bq = big_query_utils.create_big_query() for build_name in _BUILDS.keys() if 'all' in args.builds else args.builds: print('====> Build: %s' % build_name) # Since get_last_completed_build() always fails due to malformatted string # error, we use get_build_metadata() instead. job = None try: job = J[build_name] except Exception as e: print('====> Failed to get build %s: %s.' % (build_name, str(e))) continue last_processed_build_number = _get_last_processed_buildnumber(build_name) last_complete_build_number = job.get_last_completed_buildnumber() # To avoid processing all builds for a project never looked at. In this case,
def setUp(self, _poll_jenkins): _poll_jenkins.return_value = {} self.J = Jenkins('http://localhost:8080')
def get_server_instance(): server = Jenkins('http://localhost:8080', username='******', password='******') return server
def get_server_instance(): jenkins_url = 'http://invoizpaid_jenkins:8080' server = Jenkins(jenkins_url, username='******', password='******') return server
import datetime from flask import Flask from jenkinsapi.jenkins import Jenkins from prettytable import PrettyTable app = Flask(__name__) J = Jenkins('http://*****:*****@app.route('/dashboard') def dashboard(): total_builds = job.get_last_buildnumber() column_names = ['tests/builds'] + (range(1, total_builds)[::-1]) t = PrettyTable() test_names = [] resultset = job.get_build_metadata( buildnumber=total_builds).get_resultset()._data for test_result in resultset['suites'][0]['cases']: test_names.append(test_result['className'] + '.' + test_result['name']) t.add_column(column_names[0], test_names) for build_number in range(1, total_builds): resultset = job.get_build_metadata( buildnumber=build_number).get_resultset()._data test_results = [] for test_result in resultset['suites'][0]['cases']: test_results.append(test_result['status']) print test_results t.add_column(str(build_number), test_results) return str(t)
def setUp(self): port = jenkinsapi_tests.systests.state['launcher'].http_port self.jenkins = Jenkins('http://localhost:%d' % port) self._delete_all_jobs() self._delete_all_views()
This example requires NestedViews plugin to be installed in Jenkins You need to have at least one job in your Jenkins to see views """ from __future__ import print_function import logging from pkg_resources import resource_string from jenkinsapi.views import Views from jenkinsapi.jenkins import Jenkins log_level = getattr(logging, 'DEBUG') logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://127.0.0.1:8080/" jenkins = Jenkins(jenkins_url) job_name = 'foo_job2' xml = resource_string('examples', 'addjob.xml') j = jenkins.create_job(jobname=job_name, xml=xml) # Create ListView in main view logger.info('Attempting to create new nested view') top_view = jenkins.views.create('TopView', Views.NESTED_VIEW) logger.info('top_view is %s', top_view) if top_view is None: logger.error('View was not created') else: logger.info('View has been created') print('top_view.views=', top_view.views.keys())
import subprocess from django.http import HttpResponseRedirect from django.shortcuts import render from django.conf import settings from jenkinsapi.jenkins import Jenkins from .forms import JobForm JENKINS_URL = os.environ.get("JENKINS_URL", 'http://localhost') #JENKINS_PORT = os.environ.get('JENKINS_PORT', 8080) JENKINS_USER = os.environ.get('JENKINS_USER', 'admin') JENKINS_PASSWORD = os.environ.get('JENKINS_PASSWORD', 'cf4a43911dc24937bbd1092c6881b708') #J = Jenkins(f"{JENKINS_URL}:{JENKINS_PORT}", JENKINS_USER, JENKINS_PASSWORD) J = Jenkins(f"{JENKINS_URL}", JENKINS_USER, JENKINS_PASSWORD) def get_jobs(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = JobForm(request.POST) # check whether it's valid: if form.is_valid(): job = form.cleaned_data['job'] status = J[job].get_last_build().get_status() try: subprocess.check_output([ 'python ' + os.path.join(settings.BASE_DIR, 'flipjenkins.py') + ' ' +
def cicd(request): if request.session.get('is_login', None): ews_accountid = request.session.get('ews_accountid') if request.method == 'GET': try: page = request.GET.get('page') rows = request.GET.get('limit') i = (int(page) - 1) * int(rows) j = (int(page) - 1) * int(rows) + int(rows) result = {} dict = [] cicds = EwsCicd.objects.filter(tab_user_id=ews_accountid) for c in cicds: dic = {} dic['id'] = c.id dic['cicd_user'] = c.cicd_user dic['cicd_url'] = c.cicd_url dic['description'] = c.description dict.append(dic) total = len(dict) dict = dict[i:j] result['code'] = 0 result['msg'] = "" result['count'] = total result['data'] = dict return JsonResponse(result, safe=False) except Exception as ex: result['code'] = 1 result['msg'] = "" result['count'] = 0 result['data'] = "" return JsonResponse(result, safe=False) if request.method == 'POST': cicd_url = request.POST.get('cicd_url') cicd_user = request.POST.get('cicd_user') cicd_passwd = request.POST.get('cicd_passwd') cicd_desc = request.POST.get('cicd_desc') if cicd_url and cicd_user and cicd_passwd: # Jenkins对象 try: if Jenkins(cicd_url, username=cicd_user, password=cicd_passwd): new_cicd = EwsCicd() new_cicd.cicd_user = cicd_user new_cicd.cicd_passwd = cicd_passwd new_cicd.cicd_url = cicd_url new_cicd.description = cicd_desc new_cicd.created_time = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime()) new_cicd.tab_user_id = ews_accountid new_cicd.save() return HttpResponse( json.dumps({ "status": 0, "msg": "接入成功" })) except Exception as ex: return HttpResponse( json.dumps({ "status": 1, "msg": "账号认证不通过" })) print(ex) else: return HttpResponse(json.dumps({"status": 2, "msg": "缺少请求参数"})) if request.method == 'DELETE': id = QueryDict(request.body).get('id') try: if any(id): EwsCicd.objects.filter(pk=id).delete() return HttpResponse(json.dumps({"status": 0})) else: return HttpResponse(json.dumps({"status": 1})) except Exception as ex: return HttpResponse(json.dumps({"status": 2}))
def get_server_instance(): jenkins_url = 'http://47.94.161.105:8080/jenkins/' server = Jenkins(jenkins_url, username='******', password='******') return server
""" Get information about currently installed plugins """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins plugin_name = 'subversion' jenkins = Jenkins('http://localhost:8080') plugin = jenkins.get_plugins()[plugin_name] print(repr(plugin))
def test_fb_add(self, jenkins_settings, tmp_job_name, global_config_file, branch): ''' test "fb.add" command :param branch: parametrized to test adding passing a branch name in the command line and without (which means "use current branch as branch name") ''' with mock.patch('cit.get_git_branch', autospec=True) as mock_get_git_branch: mock_get_git_branch.return_value = 'new-feature' with mock.patch('cit.get_git_user', autospec=True) as mock_get_git_user: mock_get_git_user.return_value = ('anonymous', '*****@*****.**') with mock.patch('cit.get_global_config_file', autospec=True) as mock_get_global_config_file: mock_get_global_config_file.return_value = str( global_config_file) argv = ['fb.add'] if branch: argv.append(branch) assert cit.app.main(argv) is None branch = 'new-feature' jenkins = Jenkins(*jenkins_settings) new_job_name = tmp_job_name + '-' + branch assert jenkins.has_job( new_job_name), "no job %s found. available: %s" % ( new_job_name, jenkins.get_jobs_list()) config_xml = jenkins.get_job(new_job_name).get_config() # ensure we configured branch correctly config = ET.fromstring(config_xml) branches_elements = list(config.findall('.//branches')) assert len(branches_elements) == 1 branches_elem = branches_elements[0] name_elem = branches_elem.findall( 'hudson.plugins.git.BranchSpec/name')[0] assert name_elem.text == branch # ensure we have updated the display name with the feature branch's name display_name_elements = list(config.findall('.//displayName')) assert len(display_name_elements) == 1 display_name_element = display_name_elements[0] assert display_name_element.text == '%s SS win32' % branch # ensure we have set the user email recipient recipient_elements = list( config.findall('.//hudson.tasks.Mailer/recipients')) assert len(recipient_elements) == 1 recipient_element = recipient_elements[0] assert recipient_element.text == '*****@*****.**' # ensure we don't have build parameters anymore params = list( config.findall('.//hudson.model.ParametersDefinitionProperty')) assert len(params) == 0 # ensure no build is triggered after the job build_triggers = list(config.findall('.//hudson.tasks.BuildTrigger')) assert len(build_triggers) == 0
def publish_results(): # If your Jenkins server has not authentication set you might want to change the following line #J = Jenkins(JENKINS_URL) J = Jenkins(JENKINS_URL, username=JENKINS_USER, password=JENKINS_PASS) print(">>>>job=%s" % args.job) print(">>>>build=%s" % args.build) print(">>>>request_id=%s" % args.request_id) job = J[args.job] build = job.get_build(int(args.build)) output = {} status = build.get_status() console = build.get_console() #revision = build.get_revision() duration = build.get_duration() # Need to cook this url = build.baseurl causes = build.get_causes() print(">>>>>status=%s" % status) print(">>>>>console_length=%s" % len(console)) #print (">>>>>revision=%s" % revision) print(">>>>>causes=%s" % causes) print(">>>>>duration=%s" % duration) output['job'] = args.job output['build_number'] = args.build output['request_id'] = args.request_id output['status'] = status output['console'] = console #output['revision'] = revision output['duration'] = str(duration) output['url'] = url #output['causes'] = causes resultset = build.get_resultset() print(">>>>>passCount=%s" % resultset._data['passCount']) print(">>>>>failCount=%s" % resultset._data['failCount']) print(">>>>>skipCount=%s" % resultset._data['skipCount']) output['pass_count'] = resultset._data['passCount'] output['fail_count'] = resultset._data['failCount'] output['skip_count'] = resultset._data['skipCount'] results = resultset.items() output['results'] = [] count = 1 for i in results: d = {} print(">>>>>>>>>>>>>item=%s name=%s" % (count, i[0])) d['name'] = i[0] print(">>>>>>>>>>>>>status=%s" % i[1].status) d['status'] = i[1].status print(">>>>>>>>>>>>>error_details=%s" % i[1].errorDetails) d['error_details'] = i[1].errorDetails print(">>>>>>>>>>>>>error_stackTrace=%s" % i[1].errorStackTrace) d['error_stack_trace'] = i[1].errorStackTrace print(">>>>>>>>>>>>>test_case=%s" % i[1].className) d['test_case'] = i[1].className #print (">>>>>>>>>>>>>causes=%s" % i[1].causes) #d['causes'] = i[1].className output['results'].append(d) count += 1 _json = json.dumps(output, sort_keys=True) print("JSON OUTPUT=%s" % _json) print("Sending results to ServiceNow") url = SNC_URL + "/api/snc/jenkinsimport/results"
def __init__(self, url, username, password): self.server = Jenkins(url, username=username, password=password)
def get_server_instance(): jenkins_url = 'http://jenkins_host:8080' server = Jenkins(jenkins_url, username='******', password='******') return server
import sqlite3 conn = sqlite3.connect('sql.sqlite') c = conn.cursor() c.execute( 'CREATE TABLE IF NOT EXISTS "logservices" ("servicename" TEXT, "logtime" TEXT, "status" TEXT)' ) conn.commit() import jenkinsapi from jenkinsapi.jenkins import Jenkins import datetime J = Jenkins('http://localhost:8080', 'root', '123456') jobs = J.keys() for job in J.keys(): if not J[job].is_enabled(): status = 'disable' elif J[job].is_running(): status = 'running' else: status = 'enable' try: c.execute("INSERT INTO logservices ({cs}, {cstatus}, {ct}) VALUES (?, ?, ?)".\ format( cs='servicename', cstatus='status', ct='logtime'),(job, status, datetime.datetime.now().strftime("%B %d, %Y"), )) except sqlite3.IntegrityError: print('ERROR: Insert fail ') conn.commit()
from jenkinsapi.jenkins import Jenkins J = Jenkins("http://localhost:8080") node = J.get_node('example_node') jobs = [] label_names = [] for label in node.get_labels(): label_names.append(label.name) # add any jobs associated with the label jobs += label.jobs for index, job in enumerate(jobs): # Filter out jobs that are not an exact match to one of a nodes labels if not J.get_job(job).get_label_expression() in label_names: jobs.pop(index) print jobs
def trigger_job(param): j = Jenkins("http://qa.sc.couchbase.com/") job = j.build_job("test_suite_dispatcher", param) print(("job started: {}".format(job)))
def upload_file(): errorMsgs = [] if request.method == 'POST': dir_name = str(uuid.uuid4()) print("Going to store file in uploads/" + dir_name) os.makedirs('uploads/' + dir_name, 0o755) #LearnCard LearnCard = request.files['learncard'] LearnFile = 'uploads/' + dir_name + '/LC_000_%s'%LearnCard.filename # LearnCard.save(LearnFile) errorMsgs += extras.validateLearnCardFile(LearnFile)['errors'] #InCard InCard = request.files['incard'] InFile = 'uploads/' + dir_name + '/IC_%03i_%s'%(0, InCard.filename) # InCard.save(InFile) errorMsgs += extras.validateInCardFile(InFile, LearnFile)['errors'] #eMail userEmail = request.form['email'] if not extras.validateEmail(userEmail): errorMsgs += ['Error: Email not valid for this version!'] #NetworkParams NetworkParams = 'uploads/' + dir_name + '/NetworkParams.json' info = {} for x in request.form.keys(): info[x] = request.form[x] with open(NetworkParams, 'w') as f: json.dump(info, f) if len(errorMsgs) != 0: message_title = 'Fail!' message_body = Markup( '<br/>'.join(errorMsgs) ) return render_template('index.html', show_fail = True, show_success = False, message_title=message_title, message_body=message_body) ###################### Success # Trigger job #J = Jenkins('http://localhost:8080', username='******', password='******', useCrumb=True) TEST = False if not TEST: J = Jenkins('http://jenkins:8080', username='******', password='******', useCrumb=True) params = {'IN_DIR': dir_name, 'IN_MAIL': userEmail} J.build_job('run-ml', params) else: run_process_test(dir_name) message_title = 'Success!' message_body = Markup('We are processing your cards. We will send you the result by e-mail to <strong>' + userEmail + '</strong>.') with open( "emails.txt" , "a+" ) as f: f.write('%s\t%s\n'%(datetime.now().strftime("%m/%d/%Y %H:%M:%S"), userEmail) ) return render_template('index.html', show_fail = False, show_success = True, message_title=message_title, message_body=message_body)
from flask import app, Flask, request from flask_restful import Api, Resource from flask_sqlalchemy import SQLAlchemy from jenkinsapi.jenkins import Jenkins app = Flask(__name__) api = Api(app) # sqlite # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' # mysql app.config[ 'SQLALCHEMY_DATABASE_URI']: Jenkins = 'mysql+pymysql://lagou4:[email protected]:23306/lagou4' app.config['jenkins'] = Jenkins('http://stuq.ceshiren.com:8020/', username='******', password='******') db = SQLAlchemy(app) # fake db app.config['db'] = [] @app.route('/') def hello(): return 'hello from ceshiren.com' class TestCase(db.Model): __tablename__ = 'lagou4_seveniruby_testcase'