2019独角兽企业重金招聘Python工程师标准>>>
HTTP验证
有时你访问网页时会碰到这种情况:
这种方式是基于HTTP协议的一种验证方式,这里可以参考HTTP协议的具体解释:
http://www.cnblogs.com/li0803/archive/2008/11/03/1324746.html
简单来说,用户浏览器向服务器申请资源,服务器先判断权限,如果没有权限会在HTTP相应401信息,代表"Unauthorized"。
这样浏览器会自动弹出如上图的对话框让用户输入用户名密码。用户输入后这些信息会被发送到服务器。在客户端发送的HTTP请求的request headers中会包含Authorization信息。例如chrome抓取的信息:
这里的Authorization:Basic d2NhZG1pbjp0cGdxYXMwOTEy是用户名密码以
>>> import base64
>>> base64.decodestring('d2NhZG1pbjp0cGdxYXMwOTEy')
'wcadmin:'
>>>
这里的问题是用户名密码虽然加密,但是很容易在HTTP传输中被拦截和解密,所以基本无安全性可言。
下面介绍了Java的处理方法,可以参考,但我自己没有测试。
http://xinyangwjb.iteye.com/blog/1824818
Apache配置
Apache中可以配置这种HTTP验证的方式。
下面的AuthType Basic就代表了这种配置。
AuthzLDAPAuthoritative off
AuthName "Windchill"
AuthType Basic
AuthBasicProvider auth-ldap
require valid-user
符合URL的请求会被auth-ldap来验证。这里是去LDAP服务器做验证,也可以配置去DB做验证,参考Apache的配置。
AuthLDAPURL "ldap://xx.yy.zz:389/ou=people,cn=aa,cn=bb,o=cc"
AuthLDAPBindDN ""
AuthLDAPBindPassword ""
Python请求URL
这里介绍使用Python请求这种HTTP验证页面的方法。
import urllib
import urllib2
import base64
def test_HTTP_authenticate():
print('logon example')
url='http://plmtest.lenovo.com/Windchill/wtcore/jsp/jmx/serverStatus.jsp'
username='wcadmin'
password='xxxx'
headers={'Authorization':'Basic %s'%base64.encodestring('%s:%s'%(username,password))}
print(username)
print(password)
print(headers)
request=urllib2.Request(url,headers=headers)
try:
f=urllib2.urlopen(request)
#print(f.read())
print(f.getcode())
except urllib2.HTTPError as he:
print('Error : %s'%he)
print(type(he))
print(he.getcode())
print(dir(he))
#f=urllib.urlopen('http://%s:%[email protected]/Windchill/wtcore/jsp/jmx/serverStatus.jsp'%(username,password))
if __name__=='__main__':
print('show example about how to use list as arguemnt')
test_HTTP_authenticate()