代码改变世界

python urllib2 Basic认证

2013-10-11 18:06  cmsd  阅读(1904)  评论(0编辑  收藏  举报

1.通过添加http header 来实现

import urllib2
from base64 import encodestring

url = 'http://202.108.1.51'
user = 'a'
passwd = 'aa' 

req = urllib2.Request(url)
basestr = encodestring('%s:%s' % (user,passwd))[:-1]
req.add_header('Authorization','Basic %s' % basestr)

f = urllib2.urlopen(req)
for i in f:
    print i

 

2.通过handler来实现

urllib2中的HTTPBasicAuthHandler 默认使用的密码管理器是HTTPPasswordMgr ,这个管理器要求你知道认证的realm,realm就是认证时弹出来的那个字符串,如下面的hello

 

我们先用默认的密码管理器来实现

import urllib2

url = 'http://202.108.1.51'
user = 'a'
passwd = 'aa'

hdlr = urllib2.HTTPBasicAuthHandler()
hdlr.add_password('hello',url,user,passwd)  ##此处需添入realm
opener = urllib2.build_opener(hdlr)
urllib2.install_opener(opener)

f = urllib2.urlopen(url)
for i in f:
    print i

 

为了更通用我们来用HTTPPasswordMgrWithDefaultRealm密码管理器来实现

import urllib2

url = 'http://202.108.1.51'
user = 'a'
passwd = 'aa'

psmg = urllib2.HTTPPasswordMgrWithDefaultRealm()
psmg.add_password(None,url,user,passwd)
hdlr = urllib2.HTTPBasicAuthHandler(psmg)
opener = urllib2.build_opener(hdlr)
urllib2.install_opener(opener)

f = urllib2.urlopen(url)
for i in f:
    print i

 

 更多信息见:http://www.cnblogs.com/ubunoon/archive/2010/08/25/1807970.html

                http://blog.csdn.net/adrianfeng/article/details/5864510