HTTP Digest认证客户端的实现
http://lwccb.blog.163.com/blog/static/116970122006727338520/
networks 2006-08-27 15:38:52 阅读34 评论0 字号:大中小 订阅
from socket import *
from md5 import *
from random import *
conn = socket(AF_INET,SOCK_STREAM)
conn.connect(("test.bj.XXX.com",80))
conn.send("GET /demo.htm HTTP/1.1/r/nAccept: text/html/r/nConnection: Keep-Alive/r/nUser-Agent: Mozilla/r/nHost: test-mediasvr.bj.intel.com/r/n/r/n")
header=conn.recv(1024)
authheader = [x for x in header.splitlines() if x.startswith("WWW-Authenticate")]
noncel = [x for x in authheader[0].split(', ') if x.startswith("nonce")]
nonce = noncel[0].split('"')[1].strip('"')
realm=authheader[0].split(', ')[0].split('=')[1].strip('"')
username = "liuweid"
passwd = "xxxxx"
A1= username + ":" + realm + ":" + passwd
HA1 = md5(A1).hexdigest()
A2 = "GET:/demo.htm"
HA2 = md5(A2).hexdigest()
nc="00000001"
cnonce=md5(str(random())).hexdigest()
qop = "auth"
response =md5(HA1+":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+HA2).hexdigest()
dig = """Authorization: Digest username="%s", realm="%s", qop="auth", algorithm="MD5", uri="/demo.htm", nonce="%s", nc=%s, cnonce="%s", response="%s"/r/n""" % (username,realm,nonce,nc,cnonce,response)
conn.send("GET /demo.htm HTTP/1.1/r/nAccept: text/html/r/nConnection: Keep-Alive/r/nUser-Agent: Mozilla/r/nHost: test-mediasvr.bj.intel.com/r/n"+dig+"/r/n")
print conn.recv(2048)
conn.close()
本程序为说明原理,没有直接调用Python的urllib2模块来实现,而是直接基于socket来实现,参考了RFC 2617,在UbuntuLinux + Apache2上调试通过.
wget工具的 --http-user, --http-passwd选项是使用类似的方法实现的.