10

얼마 전에 Mechanize 모듈을 사용 중이 었는데 이제는 요청 모듈을 사용하려고합니다.
(Python mechanize doesn't work when HTTPS and Proxy Authentication required)파이썬 요청 모듈을 사용하여 프록시 인증 (digest auth 필요)을 전달하는 방법

인터넷에 접속할 때 프록시 서버를 통과해야합니다.
프록시 서버에 인증이 필요합니다. 나는 다음과 같은 코드를 썼다.

import requests 
from requests.auth import HTTPProxyAuth 

proxies = {"http":"192.168.20.130:8080"} 
auth = HTTPProxyAuth("username", "password") 

r = requests.get("http://www.google.co.jp/", proxies=proxies, auth=auth) 

위의 코드는 프록시 서버가 기본 인증을 요구할 때 잘 작동합니다.
이제 프록시 서버에서 다이제스트 인증이 필요한 경우 어떻게해야하는지 알고 싶습니다.
HTTPProxyAuth가 다이제스트 인증에서 효과적이지 않은 것 같습니다 (r.status_code는 407을 반환 함).

답변

7

의 내가 프록시 인증에 사용할 수있는 클래스를 작성하여 다이제스트 인증을 사용할 수 있습니다 (인증 다이제스트 기준).
requests.auth.HTTPDigestAuth에서 거의 모든 코드를 빌 렸습니다.

import requests 
import requests.auth 

class HTTPProxyDigestAuth(requests.auth.HTTPDigestAuth): 
    def handle_407(self, r): 
     """Takes the given response and tries digest-auth, if needed.""" 

     num_407_calls = r.request.hooks['response'].count(self.handle_407) 

     s_auth = r.headers.get('Proxy-authenticate', '') 

     if 'digest' in s_auth.lower() and num_407_calls < 2: 

      self.chal = requests.auth.parse_dict_header(s_auth.replace('Digest ', '')) 

      # Consume content and release the original connection 
      # to allow our new request to reuse the same one. 
      r.content 
      r.raw.release_conn() 

      r.request.headers['Authorization'] = self.build_digest_header(r.request.method, r.request.url) 
      r.request.send(anyway=True) 
      _r = r.request.response 
      _r.history.append(r) 

      return _r 

     return r 

    def __call__(self, r): 
     if self.last_nonce: 
      r.headers['Proxy-Authorization'] = self.build_digest_header(r.method, r.url) 
     r.register_hook('response', self.handle_407) 
     return r 

사용법 : 아직 여기까지 당신의 사람들을 위해

proxies = { 
    "http" :"192.168.20.130:8080", 
    "https":"192.168.20.130:8080", 
} 
auth = HTTPProxyDigestAuth("username", "password") 

# HTTP 
r = requests.get("http://www.google.co.jp/", proxies=proxies, auth=auth) 
r.status_code # 200 OK 

# HTTPS 
r = requests.get("https://www.google.co.jp/", proxies=proxies, auth=auth) 
r.status_code # 200 OK 
+2

오류가 발생합니다 : 'HTTPProxyDigestAuth'객체에 'last_nonce'속성이 없습니다. 수업을하려고 할 때. 나는 그것을 들여다 볼 것이다. – MattClimbs

+3

이제 요청을 구현할 필요가 없습니다. 이제 요청은 프록시를 지원합니다. 'proxies = { 'https': 'https : // user : password @ ip : port'}; r = requests.get ('https : // url', proxies = 프록시)'http://docs.python-requests.org/ko/latest/user/advanced/ – BurnsBA

+0

@BurnsBA @MattClimbs @yutaka 파이썬 3에서 https와'user : password @ ip : port'를 사용하여 요청이 잘 작동하는지 확인하십시오. – jamescampbell

0

당신은 requests.auth.HTTPDigestAuth를 사용하는 대신 requests.auth.HTTPProxyAuth

+0

프록시 인증 (다이제스트 인증 기반)을 전달하고 싶습니다. 그것은 일반적인 다이제스트 인증과 다릅니다. 그래서 HTTPDigestAuth를 확장해야했습니다 (아래 참조). – yutaka

0
import requests 
import os 


# in my case I had to add my local domain 
proxies = { 
    'http': 'proxy.myagency.com:8080', 
    'https': '[email protected]:[email protected]:8080', 
} 


r=requests.get('https://api.github.com/events', proxies=proxies) 
print(r.text) 
1

자신을 구현할 필요가 없습니다!

은 이제 요청은 프록시에 대한 지원이 포함되어 있습니다 :

proxies = { 'https' : 'https://user:[email protected]:port' } 
r = requests.get('https://url', proxies=proxies) 

이 내 인생을 저장 @BurnsBA에서 답이다 docs

에 대한 자세한 내용을 참조하십시오.

참고 : 프록시 서버의 IP 주소를 사용해야합니다!