Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Last active January 5, 2024 08:37
Show Gist options
  • Save m-x-k/7c7e02de0abfb47b07d8e62aed93d00d to your computer and use it in GitHub Desktop.
Save m-x-k/7c7e02de0abfb47b07d8e62aed93d00d to your computer and use it in GitHub Desktop.
Python script to help get jenkins job console output
#!/usr/bin/env python
import re
import argparse
import requests
jenkins_url = "https://localhost:8080"
# Add new jobs here:
jobs = {
"my_job": "/folder/subfolder/jobname"
}
def call_jenkins(path):
return requests.get("{0}/{1}".format(jenkins_url, path), verify=False)
def build_jenkins_path(job):
paths = job.split("/")
path = "".join([p + "/job/" for p in paths])
return re.sub("/job/$", "",path)
def get_job_console_output(job):
path = build_jenkins_path(job)
url = "{0}{1}".format(path, "/lastBuild/consoleText")
return call_jenkins(url)
if __name__ == '__main__':
# Example: python jenkinsJobConsoleOutput.py -j my_job
parser = argparse.ArgumentParser()
parser.add_argument('-j', dest="job", help="Choose job to get console logs from")
args = parser.parse_args()
job_path = jobs.get(args.job)
result = get_job_console_output(job_path).text
print(result)
@StanSilas
Copy link

Thanks for sharing this.
How do I add user name and password authentication?
currently it shows":

Authentication required
<!--
You are authenticated as: anonymous
Groups that you are in:
  
Permission you need to have (but didn't): hudson.model.Hudson.Read
 ... which is implied by: hudson.security.Permission.GenericRead
 ... which is implied by: hudson.model.Hudson.Administer
-->

</body></html>                                                                                                                                                                                                                 

@m-x-k
Copy link
Author

m-x-k commented Jun 20, 2019

Jenkins recently updated their API's to support tokens.

https://wiki.jenkins.io/display/JENKINS/Remote+access+API

So you'll have generate a token for your user. Once you have this you can add an authorisation header to the outgoing request:

def call_jenkins(path):
    return requests.get("{0}/{1}".format(jenkins_url, path), headers={'Authorization': 'Basic <USERNAME:TOKEN>'}, verify=False)

Note: <USERNAME:TOKEN> should be base64 encoded.

@BalakrishnaS1
Copy link

I sent the request from postman and got Status 200 Ok. I took the Authorization key from the header section and used it in my script. Now I am getting the below error:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment