# coding:utf-8 from jenkinsapi.jenkins import Jenkins # 实例化Jenkins对象,传入地址+账号+密码 j = Jenkins("http://127.0.0.1:8080", username='chen', password='chen') # 获取所有的job名称 print j.keys() # 获取pipeline_test这个job最后一次构建成功的构建编号 print j['pipeline_test'].get_last_good_build() # 获取Jenkins运行的地址 print j.base_server_url()
打印如下
['pipeline_test'] pipeline_test #6
http://127.0.0.1:8080
启动构建
j.build_job('pipeline_test')
提示:
Traceback (most recent call last): File "E:/guchen/jenkin_api/jenkins_api.py", line 18, in <module> j.build_job('pipeline_test') File "E:guchenvenvlibsite-packagesjenkinsapijenkins.py", line 174, in build_job self[jobname].invoke(build_params=params or {}) File "E:guchenvenvlibsite-packagesjenkinsapijob.py", line 209, in invoke allow_redirects=False File "E:guchenvenvlibsite-packagesjenkinsapiutils equester.py", line 158, in post_and_confirm_status response.text.encode('UTF-8') jenkinsapi.custom_exceptions.JenkinsAPIException: Operation failed. url=http://127.0.0.1:8080/job/pipeline_test/build, data={'json': '{"redirectTo": ".", "parameter": [], "statusCode": "303"}'}, headers={'Content-Type': 'application/x-www-form-urlencoded'}, status=403, text=<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <title>Error 403 No valid crumb was included in the request</title> </head> <body><h2>HTTP ERROR 403</h2> <p>Problem accessing /job/pipeline_test/build. Reason: <pre> No valid crumb was included in the request</pre></p><hr><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.z-SNAPSHOT</a><hr/> </body> </html>
打开对应的:url=http://127.0.0.1:8080/job/pipeline_test/build
提示说必须使用post请求触发构建。
单击Proceed按钮,F12抓取一下通信:
发现这个请求确实需要post方式,而且需要传参数:'Jenkins-Crumb': '2461db55f9ead818bd4ef801ac566bb5', 'json': {'Jenkins-Crumb': '2461db55f9ead818bd4ef801ac566bb5'}
那我们就用代码先get请求一下,再post请求一下看能不能构建成功
requests.get('http://127.0.0.1:8080/job/pipeline_test/build') payload = { 'Jenkins-Crumb': '2461db55f9ead818bd4ef801ac566bb5', 'json': {'Jenkins-Crumb': '2461db55f9ead818bd4ef801ac566bb5'} } requests.get('http://127.0.0.1:8080/job/pipeline_test/build') requests.post('http://127.0.0.1:8080/job/pipeline_test/build', payload)
刚开始还可以,写博客时又不行了!!!懵了