Problem with urllib2 and authentification

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Apr 22 15:04:11 EDT 2008


En Tue, 22 Apr 2008 11:24:20 -0300, Miguel Beltran R. <yourpadre at gmail.com> escribió:

> Using this script for connect to Zope I have this error
>
> ---script:
> import urllib2
>
> protocolo='http://'
> servidor='10.28.1.239/'
> pagina='manage'
> fullurl=protocolo+servidor+pagina
>
> aut=urllib2.HTTPBasicAuthHandler()
> aut.add_password(realm=None,
>                  uri=servidor,
>                  user='myadmin',
>                  passwd='mypass')
> opener=urllib2.build_opener(aut, urllib2.HTTPHandler(debuglevel=1))
>
> print opener.open(fullurl).read()
>
>
> ---Error:
> connect: (10.28.1.239, 80)
> send: 'GET /manage HTTP/1.1\r\nAccept-Encoding: identity\r\nHost:
> 10.28.1.239\r\nConnection: close\r\nUser-agent:
> Python-urllib/2.4\r\n\r\n'
> reply: 'HTTP/1.1 401 Unauthorized\r\n'
> header: Server: Zope/(Zope 2.10.5-final, python 2.4.4, win32) ZServer/1.1
> header: Date: Tue, 22 Apr 2008 14:14:45 GMT
> header: Bobo-Exception-Line: 713
> header: Content-Length: 884
> header: Bobo-Exception-Value: See the server error log for details
> header: Content-Type: text/html; charset=iso-8859-15
> header: Bobo-Exception-Type: Unauthorized
> header: Connection: close
> header: Bobo-Exception-File: HTTPResponse.py
> header: WWW-Authenticate: basic realm="Zope"

Note the realm="Zope" above. You should add a password for such exact realm, or use an HTTPPasswordMgrWithDefaultRealm instead.
Also, the uri argument to add_password is wrong. Try this:

protocolo='http://'
servidor='10.28.1.239'
pagina='/manage'
fullurl=protocolo+servidor+pagina

aut=urllib2.HTTPBasicAuthHandler()
aut.add_password(realm="Zope",
                  uri=servidor,
                  user='myadmin',
                  passwd='mypass')
opener=urllib2.build_opener(aut, urllib2.HTTPHandler(debuglevel=1))
print opener.open(fullurl).read()

The other alternative would be:

pmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pmgr.add_password(None, uri=servidor, user=..., passwd=...)
aut = urllib2.HTTPBasicAuthHandler(pmgr)
opener=urllib2.build_opener(aut, urllib2.HTTPHandler(debuglevel=1))

-- 
Gabriel Genellina




More information about the Python-list mailing list