[python]代码库
1 #! /usr/bin/env python
2
3 import urllib2
4
5 LOGIN = 'wesc'
6 PASSWD = "you'llNeverGuess"
7 URL = 'http://localhost'
8
9 def handler_version(url):
10 from urlparse import urlparse as up
11 hdlr = urllib2.HTTPBasicAuthHandler()
12 hdlr.add_password('Archives',up(url)[1],LOGIN,PASSWD)
13 opener = urllib2.build_opener(hdlr)
14 urllib2.install_opener(opener)
15 return url
16
17 def request_version(url):
18 from base64 import encodestring
19 req = urllib2.Request(url)
20 b64str = encodestring('%s:%s' % (LOGIN,PASSWD))[:-1]
21 req.add_header("Authorization","Basic %s" % b64str)
22 return req
23
24 for funcType in ('handler','request'):
25 print '*** Using %s:' % funcType.upper()
26 url = eval('%s_version' % funcType)(URL)
27 f = urllib2.urlopen(url)
28 print f.readline()
29 f.close()
30
======================================
运行结果:
[root@dogood pycode]# python urlopenAuth.py
*** Using HANDLER:
<html>
*** Using REQUEST:
<html>
[root@dogood pycode]#