简体   繁体   English

Python和401响应

[英]Python And 401 response

I just wanna ask how to make a connection [user+pass] with A page that give you 401 response. 我只想问一下如何与A页面建立[user + pass]连接,从而获得401响应。

For example in php its seem like that 例如在php中,它看起来像那样

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://192.168.1.1/');

curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_TIMEOUT, 4);

$result = curl_exec($ch);

$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);

If you're looking for something simple, the requests library is as simple as it could get. 如果您正在寻找简单的东西,那么requests库将尽可能简单。 Here is a simple example of basic authentication from the docs: 这是来自文档的基本身份验证的简单示例:

>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>

您可以使用urllib2模块-http: //docs.python.org/2/library/urllib2.html

There are three good options here. 这里有三个不错的选择。

First, you can use urllib2 (Python 2) or urllib (Python 3), which are built in, and pretty easy to use. 首先,您可以使用内置的urllib2 (Python 2)或urllib (Python 3),并且非常易于使用。

Second, you can use an even easier third-party library like requests . 其次,您可以使用甚至更简单的第三方库(例如requests (Often, code that takes a dozen lines to write with curl or urllib is a two-liner with requests .) (通常,需要十几行代码才能使用curlurllib编写的代码是带有requests的两层代码。)

Finally, since you already know how to use php's low-level libcurl wrappers, there are a few different third-party alternatives for Python that are nearly identical. 最后,由于您已经知道如何使用php的低级libcurl包装器,因此有一些几乎完全相同的Python第三方替代方法。 See this search , and look through pycurl , pycurl2 , and pyclibcurl to see which one feels most familiar. 查看此搜索 ,并浏览pycurlpycurl2pyclibcurl以了解最熟悉的哪个。

You're looking for the Keyword Basic HTTP Authentication . 您正在寻找关键字Basic HTTP Authentication

I do not recommend using 3rd party modules if you won't be going further than doing that. 如果您不打算这样做,我不建议您使用第三方模块。 If you will, the requests library already suggested is a great choice. 如果您愿意,已经建议的requests库是一个不错的选择。

The following example is taken from the urllib2 docs : 以下示例取自urllib2 docs

import urllib2
# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM