python基本身份验证检查

时间:2014-03-04 10:45:20

标签: python http authentication

如果在执行所需命令之前需要基本的http身份验证,我是否尝试制作检查网页的脚本。

我很抱歉,但我不理解在python上与此检查相关的库和命令,我试图搜索它但未能找到任何有用的信息。

例如,我需要脚本来检查www.google.com页面是否要求提供凭据以查看页面,然后完成命令。

1 个答案:

答案 0 :(得分:3)

如果服务器希望客户端使用基本身份验证,它将使用包含单词WWW-Authenticate的{​​{1}}标头响应请求而无需此类身份验证。请参阅HTTP RFC的Basic Authentication Scheme部分。

使用标准Python库,您可以使用:

进行测试
'Basic'

演示:

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