Python和401响应

时间:2012-11-05 20:14:40

标签: python login passwords

我只是想问一下如何与一个给你401响应的页面建立连接[user + pass]。

例如在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);

4 个答案:

答案 0 :(得分:1)

如果您正在寻找简单的东西,requests库就像它可以获得的一样简单。以下是文档中basic authentication的一个简单示例:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这里有三个不错的选择。

首先,您可以使用内置的urllib2(Python 2)或urllib(Python 3),并且非常易于使用。

其次,您可以使用更简单的第三方库,例如requests。 (通常,使用curlurllib编写十几行的代码是requests的两行代码。)

最后,既然你已经知道如何使用php的低级libcurl包装器,那么Python的一些不同的第三方替代方案几乎完全相同。请参阅this search,然后查看pycurlpycurl2pyclibcurl,了解哪一个最为熟悉。

答案 3 :(得分:0)

您正在寻找关键字基本HTTP身份验证

如果您不想进一步使用,我建议您不要使用第三方模块。如果愿意,已建议的requests库是一个很好的选择。

以下示例来自the 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)
相关问题