使用 Python 请求模块进行 HTTP 摘要/基本身份验证

2024-03-31

我的目标是能够解析html/xml data从受密码保护的页面,然后根据我需要发送的数据(时间戳)xml commands到另一台设备。我尝试访问的页面是由 IP 设备生成的网络服务器。 另外,如果用其他语言更容易完成,请告诉我。 我的编程经验很少(一门 C 编程课)

我尝试过使用基本和摘要身份验证请求。我仍然无法获得身份验证,这阻止了我进一步发展。

这是我的尝试:

import requests
from requests.auth import HTTPDigestAuth

url='http://myUsername:[email protected] /cdn-cgi/l/email-protection/cgi/metadata.cgi?template=html'
r = requests.get(url, auth=HTTPDigestAuth('myUsername', 'myPassword'))        
r.status_code

print(r.headers) 
print(r.status_code)

Output:

401 
CaseInsensitiveDict({'Content-Length': '0', 'WWW-Authenticate': 'Digest realm="the realm of device", nonce="23cde09025c589f05f153b81306928c8", qop="auth"', 'Server': 'Device server name'})

我也尝试过BasicAuth与 Requests 并获得相同的输出。我都尝试过,包括user:pass@在 url 内,而不是。尽管当我将该输入放入浏览器时它可以工作。

我认为请求处理了标头数据Digest/BasicAuth但也许我还需要包含标题?

我使用了 Live HTTP headers(firefox) 并得到了这个:

GET /cgi/metadata.cgi?template=html
HTTP/1.1 
Host: [Device IP] 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-US,en;q=0.5 
Accept-Encoding: gzip, deflate DNT: 1 Connection: keep-alive
HTTP/1.1 401 Unauthorized WWW-Authenticate: Digest realm="Device Realm", nonce="a2333eec4cce86f78016343c48382d21", 
qop="auth" 
Server: Device Server Content-Length: 0

这两个请求是独立的:

r = requests.get(url, auth=HTTPDigestAuth('user', 'pass')) 
response = requests.get(url) #XXX <-- DROP IT

第二个请求不发送任何凭据。因此,它获得认可也就不足为奇了401 Unauthorizedhttp 响应状态。

要解决这个问题:

  1. 使用相同的url正如您在浏览器中使用的那样。降低digest-auth/auth/user/pass在最后。这只是请求文档中的一个示例
  2. Print r.status_code代替response.status_code看看是否成功。

为什么要在 url 和 in 中使用用户名/密码auth范围?从 URL 中删除用户名/密码。要查看发送的请求和响应标头,您可以启用日志记录/调试 http://docs.python-requests.org/en/latest/api/#api-changes:

import logging
import requests
from requests.auth import HTTPDigestAuth

# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, 
# and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
try:
    import httplib
except ImportError:
    import http.client as httplib

httplib.HTTPConnection.debuglevel = 1

logging.basicConfig(level=logging.DEBUG) # you need to initialize logging, 
                      # otherwise you will not see anything from requests

# make request
url = 'https://example.com/cgi/metadata.cgi?template=html'
r = requests.get(url, auth=HTTPDigestAuth('myUsername', 'myPassword'),
                 timeout=10)
print(r.status_code)
print(r.headers)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 请求模块进行 HTTP 摘要/基本身份验证 的相关文章

随机推荐