2011-12-08 67 views
3

我試圖用機械化與一個非常挑剔的遺留系統自動交互授權。特別是,在第一次登錄頁面後的授權必須與每一個5.20你從系統的請求一起發送。不幸的是,Mechanize似乎只是在第一次獲得401 Unauthorized錯誤後才發送授權。有沒有辦法讓它每次發送授權?機械化Python和不首先得到一個401錯誤

下面是一些示例代碼:

br.add_password("http://example.com/securepage", "USERNAME", "PASSWORD", "/MYREALM") 
br.follow_link(link_to_secure_page) # where the url is the previous URL 

這是我從調試得到響應機械化:

send: 'GET /securepage HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: example.com\r\nReferer: http://example.com/home\r\nConnection: close\r\nUser-Agent: Python-urllib/2.7\r\n\r\n' 
reply: 'HTTP/1.1 401 Unauthorized\r\n' 
header: Server: Tandy1000Web 
header: Date: Thu, 08 Dec 2011 03:08:04 GMT 
header: Connection: close 
header: Expires: Tue, 01 Jan 1980 06:00:00 GMT 
header: Content-Type: text/html; charset=US-ASCII 
header: Content-Length: 210 
header: WWW-Authenticate: Basic realm="/MYREALM" 
header: Cache-control: no-cache 
send: 'GET /securepage HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: example.com\r\nReferer: http://example.com/home\r\nConnection: close\r\nAuthorization: Basic VVNFUk5BTUU6UEFTU1dPUkQ=\r\nUser-Agent: Python-urllib/2.7\r\n\r\n' 
reply: 'HTTP/1.1 200 OK\r\n' 
header: Server: Tandy1000Web 
header: Date: Thu, 08 Dec 2011 03:08:07 GMT 
header: Connection: close 
header: Last-Modified: Thu, 08 Dec 2011 03:08:06 GMT 
header: Expires: Tue, 01 Jan 1980 06:00:00 GMT 
header: Content-Type: text/html; charset=UTF-8 
header: Content-Length: 33333 
header: Cache-control: no-cache 

的問題是,違背了現代Web應用程序應該發生什麼了GET要求,首先點擊401錯誤,我得到錯誤的頁面。我已經使用CURL和urllib2進行了確認,如果我通過在第一個請求中傳遞auth標頭直接打開URL,我會得到正確的頁面。

如何告訴機械化總是發送AUTH頭,避免了第一401錯誤任何提示?這需要在客戶端修復。我無法修改服務器。

+0

你有沒有想出解決辦法? – ytjohn

+0

否定的。由於此評論(七月下旬2013年)的寫作,我還沒有找到答案。當我找到答案或其他人提供答案時,我會確保接受答案。 – Pridkett

+0

自從我上次問,我設法通過將報頭工作了這一點。 – ytjohn

回答

2
from base64 import b64encode 
import mechanize 

url = 'http://192.168.3.5/table.js' 
username = 'admin' 
password = 'password' 

# I have had to add a carriage return ('%s:%s\n'), but 
# you may not have to. 
b64login = b64encode('%s:%s' % (username, password)) 

br = mechanize.Browser() 

# # I needed to change to Mozilla for mine, but most do not 
# br.addheaders= [('User-agent', 'Mozilla/5.0')] 

br.addheaders.append( 
    ('Authorization', 'Basic %s' % b64login) 
) 

br.open(url) 
r = br.response() 
data = r.read() 

print data