Reading time: 14 – 23 minutes
Com accedir a un serividor HTTP amb les pàgines protegides amb usuari i password del tipus 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
L’autentació que usa l’Abyss Webserver per defecte és la del tipus explicada en aquest exemple.