2012-11-05 98 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查看哪些人感到最熟悉。