Skip to main content
 首页 » 编程设计

python之HTTP 摘要认证 python

2025年01月19日14youxin

我的目标是访问一个使用 python 使用 HTTP 身份验证的网站。我可以从我的网络浏览器打开网站, header 告诉我应该使用 HTTBDigestAuth:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip, deflate 
Accept-Language: en-US,en;q=0.5 
Authorization: Digest username="user", realm="CG Downloads", nonce="cTN0pKxqBQA=e46ad250f42f73e9076ebc97c417f0d38bac094a", uri="/fileadmin/teaching/2017/WS/adip/exercises/adip-uebung-00-.pdf", algorithm=MD5, response="5a57ddbcd1b20444100a91b1967a2782", qop=auth, nc=00000001, cnonce="5a6b041b4113bb9a" 
Connection: keep-alive 
Cookie: fe_typo_user=76b7e7e25372f782d94e91b51b854568 
Host: cg.cs.uni-bonn.de 
Referer: http://cg.cs.uni-bonn.de/de/lehre/ws-2017/vorlesung-algorithmisches-denken-und-imperative-programmierung/ 
Upgrade-Insecure-Requests: 1 
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0 

但是,当我尝试使用请求和 HTTPDigestAuth 访问该页面时,我收到“401 Unauthorized”作为响应。

import logging 
import requests 
from requests.auth import HTTPDigestAuth 
 
try: 
    import httplib 
except ImportError: 
    import http.client as httplib 
 
httplib.HTTPConnection.debuglevel = 1 
 
logging.basicConfig(level=logging.DEBUG)  
 
url = 'http://cg.cs.uni-bonn.de/fileadmin/teaching/2017/WS/adip/exercises/adip-uebung-00-.pdf' 
response = requests.get(url, auth=HTTPDigestAuth('user', 'pass'), 
                 timeout=10) 
print(response.status_code) 
print(response.headers) 
print(r.text) 

是我使用了错误的授权方法还是我的代码有误?我很感激你能给我的任何帮助。

编辑: 我正在尝试访问 cg.cs.uni-bonn.de 上的网站,例如 http://cg.cs.uni-bonn.de/fileadmin/teaching/2017/WS/adip/exercises/adip-uebung-00-.pdf

请您参考如下方法:

您只需将值传递给 auth=HTTPDigestAuth('user', 'pass'),如下所示:

user = 'admin'    # change to your username 
pass = '123456'    # change to your password 
... 
response = requests.get(url, auth=HTTPDigestAuth(user, pass), 
             timeout=10) 
...