[Python] Using Basic HTTP Authentication

To use urllib2 to access content that requires HTTP authentication, you need to create an OpenerDirector with a HTTPBasicAuthHandler. With HTTPBasicAuthHandler, add the authentication details by calling its add_password method. It takes in four parameters – realm, uri, user and passwd.

The user and passwd are, quite obviously, the user name and password. The uri specifies the location where the user name and password applies. If there is only one location, this is usually specified as a string. However, if it can also be applied to more locations, you specify the locations as a sequence. The realm is the name of protected area where the authentication is applied to. You can get the realm from your browser, by trying to access the protected area.

With the handler created, build an opener that uses this handler. Then, use the opener to access the protected site or webpage. For example:

import urllib2

authHandler = urllib2.HTTPBasicAuthHandler()
    
authHandler.add_password(
    realm="Protected Area",
    uri="http://local.intranet",
    # If there were multiple URIs then we can specify then like this:
    # uri = ["site1", "site2"]

    user="user", 
    passwd="my_password")
opener = urllib2.build_opener(authHandler)
    
content = opener.open("http://192.168.1.254")
print content.read()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: