python: Autenticación HTTP de tipo basic-scheme

Traducción del original en catalán. Léela en: CatalàEnglish

Cómo acceder a un servidor HTTP con las páginas protegidas con usuario y password del tipo Basic Authentication Scheme.

import urllib2
<br>
theurl = 'http://host:port'
username = 'theuser'
password = 'thepass'
<br>
# this creates a password manager
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# because we have put None at the start it will always use this
# username/password combination
passman.add_password(None, theurl, username, password)
# create the AuthHandler
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# Return an OpenerDirector instance, which chains the handlers in the
# order given Return an OpenerDirector instance, which chains the
# handlers in the order given
opener = urllib2.build_opener(authhandler)
# Install an OpenerDirector instance as the default global opener
urllib2.install_opener(opener)
# Open the URL url, which can be either a string or a Request object.
pagehandle = urllib2.urlopen(theurl)
lines =  pagehandle.readlines()
<br>
for line in lines:
    print line

La autenticación que usa el Abyss Webserver por defecto es la del tipo explicado en este ejemplo.