2014-03-06 2 views
3

mechanize를 사용하여 페이지에 로그인하고 정보를 검색하고 싶습니다.python mechanize를 사용하여 NTLM 인증으로 페이지에 로그인하십시오.

r = br.open('http://intra') 
File "bui...e\_mechanize.py", line 203, in open 
File "bui...g\mechanize\_mechanize.py", line 255, 
in _mech_openmechanize._response.httperror_seek_wrapper: HTTP Error 401: Unauthorized 

이 내 코드는 지금까지입니다 : 내가 잘못 뭐하는 거지

import mechanize 
import cookielib 

# Browser 
br = mechanize.Browser() 

# Cookie Jar 
cj = cookielib.LWPCookieJar() 
br.set_cookiejar(cj) 

# Browser options 
br.set_handle_equiv(True) 
# br.set_handle_gzip(True) 
br.set_handle_redirect(True) 
br.set_handle_referer(True) 
br.set_handle_robots(False) 

# Follows refresh 0 but not hangs on refresh > 0 
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) 

# If the protected site didn't receive the authentication data you would 
# end up with a 410 error in your face 
br.add_password('http://intra', 'myusername', 'mypassword') 

# User-Agent (this is cheating, ok?) 
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] 
# Open some site, let's pick a random one, the first that pops in mind: 
# r = br.open('http://google.com') 
r = br.open('http://intra') 
html = r.read() 

# Show the source 
print html 

내가 뭔가를 인증하려고하지만 당신이 아래에 볼 수 있습니다하지만 그냥 오류 코드 HTTP 401 실패? 예를 들어 http://intra (내부 페이지)을 방문하십시오. 크롬, 그것은 창문을 열고 사용자 이름/비밀 번호를 한 번 물어 다음 모두 좋다. 이 같은 오픈 모습을 팝업

의 대화 :이 뒤에 이유를 찾을 관리

enter image description here

답변

2

reaserch의 톤 후.

기계적으로 지원되지 않는 사이트 인 NTLM authentication을 찾았습니다. here을 언급 한 바와 같이,

import sys 
import urllib2 
import mechanize 
from ntlm import HTTPNtlmAuthHandler 

print("LOGIN...") 
user = sys.argv[1] 
password = sys.argv[2] 
url = sys.argv[3] 

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, url, user, password) 
# create the NTLM authentication handler 
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) 

browser = mechanize.Browser() 
handlersToKeep = [] 

for handler in browser.handlers: 
    if not isinstance(handler, 
    (mechanize._http.HTTPRobotRulesProcessor)): 
     handlersToKeep.append(handler) 

browser.handlers = handlersToKeep 
browser.add_handler(auth_NTLM) 

response = browser.open(url) 
response = browser.open("http://www.the-site.com") 
print(response.read()) 

마지막 요구 사항을 기계화 패치하기 : 이 사이트의 인증 메커니즘을 발견하는 데 도움이 될 수 있습니다 :

wget -O /dev/null -S http://www.the-site.com/ 

그래서 코드를 조금 수정 된

--- _response.py.old 2013-02-06 11:14:33.208385467 +0100 
+++ _response.py 2013-02-06 11:21:41.884081708 +0100 
@@ -350,8 +350,13 @@ 
      self.fileno = self.fp.fileno 
     else: 
      self.fileno = lambda: None 
-  self.__iter__ = self.fp.__iter__ 
-  self.next = self.fp.next 
+ 
+  if hasattr(self.fp, "__iter__"): 
+   self.__iter__ = self.fp.__iter__ 
+   self.next = self.fp.next 
+  else: 
+   self.__iter__ = lambda self: self 
+   self.next = lambda self: self.fp.readline() 

    def __repr__(self): 
     return '<%s at %s whose fp = %r>' % (
0

@theAlse : 세션 쿠키를 별도로 처리해야합니까? 귀하의 접근 방식을 사용하여 SSO 서버를 인증했지만 두 번째 "browser.open"호출에서 주 사이트 (ServiceNow)에 액세스 할 때 나는 여전히 401 : Unauthorized 오류가 발생합니다.

machize_response.py 파일의 디버그 메시지를 방문하여 방문한 URL을 표시했는데 보조 SSO 서버가 있다는 것에 놀랐습니다.

$ python s3.py 
LOGIN... 
[_DEBUG] Visiting https://sso.intra.client.com 
[_DEBUG] Got past the first open statement. 
[_DEBUG] Visiting https://clienteleitsm.service-now.com 
[_DEBUG] Visiting <Request for https://ssointra.web.ipc.us.client.com/ssofedi/public/saml2sso?SAMLRequest=lVLB--snipped--&RelayState=https%3a%2f%2fclienteleitsm.service-now.com%2fnavpage.do> 
[_DEBUG] Visiting <Request for https://ssointra.web.ipc.us.client.com/ssofedi/redirectjsp/FederationRedirectWDA.jsp?SAMLRequest=lVLBb--snipped--&SMPORTALURL=https%3A%2F%2Fssointra.web.ipc.us.client.com%2Fssofedi%2Fpublic%2Fsaml2sso> 
[_DEBUG] Visiting <Request for https://ssointra.web.ipc.us.client.com/SSOI/ntlm/RedirectToWDA.jsp?TYPE=33554433&REALMOID=--snipped--%3D%26RelayState%3dhttps$%3a$%2f$%2fclienteleitsm%2eservice-now%2ecom$%2fnavpage%2edo%26SMPORTALURL%3dhttps$%3A$%2F$%2Fssointra%2eweb%2eipc%2eus%2eclient%2ecom$%2Fssofedi$%2Fpublic$%2Fsaml2sso> 
[_DEBUG] Visiting <Request for https://ssointra.web.ipc.us.client.com/SSOI/ntlm/WDAProtectedPage.jsp?Target=HTTPS://ssointra.--snipped--&RelayState=https%3A%2F%2Fclienteleitsm.service-now.com%2Fnavpage.do&SMPORTALURL=https%3A%2F%2Fssointra.web.ipc.us.client.com%2Fssofedi%2Fpublic%2Fsaml2sso> 
[_DEBUG] Visiting <Request for https://sso.intra.client.com/siteminderagent/ntlm/creds.ntc?CHALLENGE=&SMAGENTNAME=--snipped--https$%3A$%2F$%2Fssointra%2eweb%2eipc%2eus%2eclient%2ecom$%2Fssofedi$%2Fpublic$%2Fsaml2sso> 

[Client-specific page about invalid username and password credential combination follows] 
<HTML> 
... 
</HTML> 

세 번째 디버그 라인 이후에 이미 많은 리디렉션 URL을 잘라 냈습니다. 임의의 문자열은 브라우저에 넣을 때 실제로 오류 페이지가있는 것과 같이 고유합니다. 그러나 IE 브라우저에서 그렇게하면 리디렉션 페이지가 표시되지 않습니다.

감사합니다.

관련 문제