Skip to content

Instantly share code, notes, and snippets.

@loa
Created September 22, 2014 12:48
Show Gist options
  • Save loa/5c13ffe50bf93bcc0789 to your computer and use it in GitHub Desktop.
Save loa/5c13ffe50bf93bcc0789 to your computer and use it in GitHub Desktop.
Python Jenkins API Auth
#!/usr/bin/env python
import base64
import os
import urllib2
username = os.environ['user']
password = os.environ['password']
# http://stackoverflow.com/questions/16907684/fetching-a-url-from-a-basic-auth-protected-jenkins-server-with-urllib2
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(None, "jenkins.tomologic.net", username, password)
urllib2.install_opener(urllib2.build_opener(auth_handler))
try:
response = urllib2.urlopen("http://jenkins.localhost/job/example/config.xml")
print response.read()
except urllib2.HTTPError, e:
print e.code
print e.header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment