2012-11-05 54 views
0

我只想问如何使一个连接[用户+传递]与一个页面,给你401响应。Python和401响应

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

[?你尝试过什么(http://whathaveyoutried.com) – thegrinner

+0

既然你显然已经知道如何使用PHP的低级别的libcurl包装,你看过Python包装器吗? – abarnert

+0

我尝试搜索但我没有找到我想要的:s – user1801082

回答

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) 
1

,该requests库是简单,因为它可以得到。下面是basic authentication的一个简单示例:

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

这就是它,谢谢 – user1801082

0

这里有三个很好的选择。

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

其次,您可以使用更容易的第三方库,如requests。 (通常情况下,代码需要十几行用curlurllib写是双内胆采用requests

最后,既然你已经知道如何使用PHP的低级别libcurl的包装,也有一些不同的第三Python的几乎相同的替代方案。请参阅this search,并通过pycurl,pycurl2pyclibcurl查看哪些人感到最熟悉。