HTTP digest client implementation
Http://lwccb.blog.163.com/blog/static/116970122006727338520/
Networks 15:38:52 read 34 comments 0 font size: LargeMediumSmall subscription
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 ()
This program illustrates the principle. It does not directly call Python's urllib2 module, but is directly implemented based on socket. According to RFC 2617, it passes debugging on ubuntulinux + apache2.
The -- http-user and -- http-passwd options of the wget tool are implemented in a similar way.