81

我正在尝试在 python 中使用基本的 HTTP 身份验证。我正在使用请求库

auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')

响应表单身份验证变量:

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie JSESSIONID=cb10906c6219c07f887dff5312fb for appdynamics/controller>]>
200
CaseInsensitiveDict({'content-encoding': 'gzip', 'x-powered-by': 'JSP/2.2', 'transfer-encoding': 'chunked', 'set-cookie': 'JSESSIONID=cb10906c6219c07f887dff5312fb; Path=/controller; HttpOnly', 'expires': 'Wed, 05 Nov 2014 19:03:37 GMT', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'no-cache', 'cache-control': 'max-age=78000', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html;charset=ISO-8859-1'})

但是当我尝试从不同位置获取数据时, - 我遇到 401 错误

<<class 'requests.cookies.RequestsCookieJar'>[]>
401
CaseInsensitiveDict({'content-length': '1073', 'x-powered-by': 'Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)', 'expires': 'Thu, 01 Jan 1970 00:00:00 UTC', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'No-cache', 'cache-control': 'no-cache', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html', 'www-authenticate': 'Basic realm="controller_realm"'})

据我了解 - 在第二个请求中没有替换会话参数。

4

6 回答 6

89

您需要使用会话对象并在每个请求中发送身份验证。该会话还将为您跟踪 cookie:

session = requests.Session()
session.auth = (user, password)

auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')
于 2014-11-04T22:54:01.743 回答
48
import requests

from requests.auth import HTTPBasicAuth
res = requests.post('https://api.github.com/user', verify=False, auth=HTTPBasicAuth('user', 'password'))
print(res)

注意:有时,我们可能会得到 SSL 错误证书验证失败,为避免,我们可以使用verify=False

于 2019-01-01T07:30:58.027 回答
22

在 Python3 中,它变得很容易:

import requests
response = requests.get(uri, auth=(user, password))
于 2020-12-14T08:50:00.807 回答
2

对于蟒蛇 2:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data = result.read()
于 2020-02-11T14:46:55.347 回答
0

以下对我有用

from requests.auth import HTTPDigestAuth
url = 'https://someserver.com'
requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
于 2021-06-08T08:05:01.543 回答
0

下面一个对我有用

#!/usr/bin/python3
import xml.etree.ElementTree as ET
import requests
from requests.auth import HTTPBasicAuth

url = 'http://172.25.38.135:600/service/xx/users'      # my URL     
response = requests.get(url, auth=HTTPBasicAuth('admin', 'adminpass!'))

string_xml = response.content
tree = ET.fromstring(string_xml)
ET.dump(tree)
于 2022-01-28T11:58:41.010 回答