Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python mechanize handle HTTP auth?

Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success.

My code looks like this.

import mechanize

project = "test"
baseurl = "http://trac.somewhere.net"
loginurl = "%s/%s/login" % (baseurl, project)
b = mechanize.Browser()
b.add_password(baseurl, "user", "secret", "some Realm")
b.open(loginurl)
like image 908
Shekhar Avatar asked Jul 08 '09 11:07

Shekhar


People also ask

Does mechanize use a real browser?

mechanize doesn't use real browsers - it is a tool for programmatic web-browsing.

What is mechanize in Python?

The mechanize module in Python is similar to perl WWW:Mechanize. It gives you a browser like object to interact with web pages. Here is an example on how to use it in a program.


2 Answers

Mechanize claims that the parameters should be uri, username and password as parameters, but you have four parameters. Four parameters are correct for urllib2.add_password, but then the first parameter should be the realm, not the uri.

http://wwwsearch.sourceforge.net/mechanize/

I'd try to change that first.

Does trac require digest? if not a next step could be to try using basic auth, as a test to see if that works, since you can add that with just addHeader:

import base64
from mechanize import Browser
browser = Browser()
browser.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (user, pwd))))
like image 150
Lennart Regebro Avatar answered Oct 14 '22 05:10

Lennart Regebro


For http authentication with mechanize you need to provide the complete url to the add_password method and not just the host base address.

import mechanize

project = "test"
baseurl = "http://trac.somewhere.net"
loginurl = "%s/%s/login" % (baseurl, project)
b = mechanize.Browser()
b.add_password(loginurl, "user", "secret", "some Realm")
b.open(loginurl)
like image 44
Yuda Prawira Avatar answered Oct 14 '22 04:10

Yuda Prawira