April 25th, 2005, 12:12 AM
urllib2 basic authentication
I have been searching google for hours. I can't seem to get this to work right. I am trying to connect to a location that requires basic authentication to view the page. But I either get 401 errors or when i try to open the page and read it, it gives me nothing. I don't understand what i am doing wrong, here is my current code.
import urllib2, sys, re, base64
from urlparse import urlparse
theurl = 'http://example.com:81'
username = 'test'
password = 'XXXXXX' # a great password
passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager
passman.add_password(None, theurl, username, password) # because we have put None at the start it will always use this username/password combination
authhandler = urllib2.HTTPBasicAuthHandler(passman) # create the AuthHandler
opener = urllib2.build_opener(authhandler) # build an 'opener' using the handler we've created
# you can use the opener directly to open URLs
# *or* you can install it as the default opener so that all calls to urllib2.urlopen use this opener
for line in urllib2.urlopen("http://example.com:81"):
Last edited by CyBerHigh; April 25th, 2005 at 12:19 AM.
April 25th, 2005, 02:52 PM
Did you try checking on ASPN?
April 25th, 2005, 04:14 PM
that is where i got that.
April 26th, 2005, 03:43 AM
For basic authentication the realm parameter should be set:
If 'my_realm' is equal to 'AuthName' in .htaccess on the web server, it should work.
passman.add_password(my_realm, theurl, username, password)...
April 26th, 2005, 07:21 AM
i don't know the ralem of this, this program is to help me manage some thing through cpanel, but i want to automate a few things. I am not sure what my host has as the authname.
and if i did, does that mean i don't create it with defualtRelm?
April 26th, 2005, 09:41 AM
On a normal web server with basic authentication it should work with default or named realms. Maybe there is more than basic authentication required.
You could try authentication without authentication handler and opener as shown in the aspn example to get more information and control on what is sent and received during login.