1

I need to access the Jenkins JSON API from a Python script. The problem is that our Jenkins installation is secured so to log in users have to select a certificate. Sadly, in Jenkins Remote Access Documentation they don't mention a thing about certificates and I tried using the API Token without success.

How can I get to authenticate from a Python script to use their JSON API?

Thanks in advance!

Rhyuk
  • 163
  • 2
  • 17

3 Answers3

1

You have to authenticate to the JSON API using HTTP Basic Auth.

To make scripted clients (such as wget) invoke operations that require authorization (such as scheduling a build), use HTTP BASIC authentication to specify the user name and the API token. This is often more convenient than emulating the form-based authentication

https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients

Here is a sample of using Basic Auth with Python.

http://docs.python-requests.org/en/master/user/authentication/

Keep in mind if you are using a Self Signed certificate on an internal Jenkin Server you'll need to turn off certificate validation OR get the certificate from the server and add it to the HTTP request

http://docs.python-requests.org/en/master/user/advanced/

strongjz
  • 4,271
  • 1
  • 17
  • 27
  • I had to use certificates :( But thanks a lot for the link which covers how to use certs with Python! I'm a Python newbie! – Rhyuk Sep 21 '16 at 21:18
0

I finally found out how to authenticate to Jenkins using certs and wget. I had to convert my pfx certificates into pem ones with cert and keys in separate files For more info about that come here. In the end this is the command I used.

wget --certificate=/home/B/cert.pem --private-key=/home/B/key.pem --no-check-certificate --output-document=jenkins.json https:<URL>
Community
  • 1
  • 1
Rhyuk
  • 163
  • 2
  • 17
0

I'm not completely sure it covers your certificate use case, but since it took me some time to find out, I still want to share this snipped that retrieves the email address for a given user name in Python without special Jenkins libraries. It uses an API token and "supports" (actually ignores) https:

def _get_email_adress(user):
    request = urllib.request.Request("https://jenkins_server/user/"+ user +"/api/json")
    #according to https://stackoverflow.com/a/28052583/4609258 the following is ugly
    context = ssl._create_unverified_context() 
    base64string = base64.b64encode(bytes('%s:%s' % ('my user name', 'my API token'),'ascii'))
    request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))

    with urllib.request.urlopen(request, context=context) as url:
        user_data = json.loads(url.read().decode())
        for property in user_data['property']:
            if property["_class"]=="hudson.tasks.Mailer$UserProperty":
                return property["address"];
Florian Straub
  • 826
  • 9
  • 18