urllib2不会进行身份验证,curl工作正常

时间:2018-01-09 00:01:53

标签: python urllib2

当我使用curl时,这可行:

curl -v https://example.org:8080/platform/3/zones --insecure --basic -u 'user:password'
* About to connect() to example.org port 8080 (#0)
*   Trying example.org... connected
* Connected to example.org (example.org) port 8080 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* warning: ignoring value of ssl.verifyhost
* skipping SSL peer certificate verification
* SSL connection using TLS_DHE_RSA_WITH_AES_256_CBC_SHA
* Server certificate:
*       subject: E=support@isilon.com,CN=Isilon Systems,OU=Isilon Systems,O="Isilon Systems, Inc.",L=Seattle,ST=Washington,C=US
*       start date: May 15 07:48:59 2014 GMT
*       expire date: May 14 07:48:59 2017 GMT
*       common name: Isilon Systems
*       issuer: E=support@isilon.com,CN=Isilon Systems,OU=Isilon Systems,O="Isilon Systems, Inc.",L=Seattle,ST=Washington,C=US
* Server auth using Basic with user 'root'
> GET /platform/3/zones HTTP/1.1
> Authorization: Basic xxxxxxxxxxxxxxxxxxxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: example.org:8080
> Accept: */*
>
< HTTP/1.1 200 Ok
< Date: Mon, 08 Jan 2018 23:44:18 GMT
< Server: Apache/2.2.31 (FreeBSD) mod_ssl/2.2.31 OpenSSL/1.0.2j-fips mod_fastcgi/2.4.6
< Allow: GET, POST, HEAD
< Transfer-Encoding: chunked
< Content-Type: application/json
<
[data omitted]

所以,我正在尝试这个Python代码:

#!/usr/bin/python
import urllib2
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None, 'https://example.org:8080/', 'user', 'password')
opener = urllib2.build_opener(
    auth_handler,
    )
urllib2.install_opener(opener)
r = urllib2.Request('https://example.org:8080/platform/3/zones')
try:
    f = urllib2.urlopen(r)
except urllib2.HTTPError as err:
    print '***', err.code, err.msg
    print err.headers
    print err.read()

然后我回来了:

*** 401 Authorization Required
Date: Mon, 08 Jan 2018 23:32:19 GMT
Server: Apache/2.2.31 (FreeBSD) mod_ssl/2.2.31 OpenSSL/1.0.2j-fips mod_fastcgi/2.4.6
WWW-Authenticate: Basic
Last-Modified: Fri, 12 May 2017 09:14:48 GMT
ETag: "2841d-31-54f5023135200"
Accept-Ranges: bytes
Content-Length: 49
Connection: close
Content-Type: application/json

{"errors":[{"message":"authorization required"}]}

可能是curl命令上的'--insecure'标志正在做某事,或者我设置auth_handler时出错了。如果你发现了什么,请告诉我。我很遗憾地在防火墙后面,不允许我到http://httpbin.org/所以我需要将我的代码移到别处以在那里进行测试。

0 个答案:

没有答案