Search code examples
pythonbasic-authentication

How to get through basic authentification with python 2.7?


I would like to let the server send email when websites do not respond not HTTP 200. I made a file with python and then crontab execute this file every single minute in my server.

However I could not access one of my website with basic auth by python's file.

servers = ("133.###.###.###:####","133.###.###.###:9200","https://########.net:1##0")
def checkroot(address):
    global result,error_detected
    conn = httplib.HTTPConnection( address )
    try:
        conn.request( "GET", "/" )
    except:
        result = result + address + "websites are down\n"
        error_detected = True
        return
    response = conn.getresponse()
    if response.status != 200:
        error_detected = True
    result = result + format_result(address,response) + "\n"
    conn.close()

for each in servers:
    checkroot(each)

Third website has basic authentification. Python version is 2.75.

I would like to be able to access the website and get correct HTTP response.


Solution

  • You'll need to pass your auth details in the connection headers for URLs requiring Basic Auth:

    from base64 import b64encode
    # This sets up the https connection
    c = HTTPSConnection("www.google.com")
    # we need to base 64 encode it
    creds = b64encode("username:password")
    headers = { 'Authorization' : 'Basic %s' %  creds }
    # then connect
    c.request('GET', '/', headers=headers)
    

    I'd recommend using the requests library though, which is much easier.