2014-03-04 60 views
0

我試圖做腳本,檢查網頁,如果它需要基本的HTTP身份驗證或不執行之前執行所需的命令。Python的基本身份驗證檢查

對不起,但我不明白在python這個檢查相關的庫和命令,我試圖搜索它,但沒有找到任何有用的信息。

例如,我需要該腳本來檢查www.google.com頁面,如果它要詢問憑據以查看頁面,或者不完成該命令。

+1

答案中缺少的一件事會讓你一年後不再接受嗎? :-) –

回答

3

如果服務器期望客戶端使用基本認證,它會向請求響應沒有與WWW-Authenticate這樣的認證,包含單詞'Basic'。請參閱HTTP RFC的Basic Authentication Scheme部分。

使用標準Python庫,你可以測試與:

from urllib2 import urlopen, HTTPError 

try: 
    response = urlopen(url) 
except HTTPError as exc: 
    # A 401 unauthorized will raise an exception 
    response = exc 
auth = response.info().getheader('WWW-Authenticate') 
if auth and auth.lower().startswith('basic'): 
    print "Requesting {} requires basic authentication".format(url) 

演示:

>>> from urllib2 import urlopen, HTTPError 
>>> url = 'http://httpbin.org/basic-auth/user/passwd' 
>>> try: 
...  response = urlopen(url) 
... except HTTPError as exc: 
...  # A 401 unauthorized will raise an exception 
...  response = exc 
... 
>>> auth = response.info().getheader('WWW-Authenticate') 
>>> if auth and auth.lower().startswith('basic'): 
...  print "Requesting {} requires basic authentication".format(url) 
... 
Requesting http://httpbin.org/basic-auth/user/passwd requires basic authentication 

要添加超時請求爲好,用途:

from urllib2 import urlopen, HTTPError 
import socket 


response = None 

try: 
    response = urlopen(url, timeout=15) 
except HTTPError as exc: 
    # A 401 unauthorized will raise an exception 
    response = exc 
except socket.timeout: 
    print "Request timed out" 

auth = response and response.info().getheader('WWW-Authenticate') 
if auth and auth.lower().startswith('basic'): 
    print "Requesting {} requires basic authentication".format(url) 
+0

謝謝,他的工作,兄弟,但你能解釋我可以在代碼中添加超時嗎? – abualameer94

+0

@ abualameer94:使用'urlopen(url,timeout = 15)'超時15秒。 –

+0

謝謝,Martijn。我添加了超時,它的工作完美,但當超過時間限制它顯示它爲和錯誤如何我可以添加超時問題的例外。 – abualameer94