- 论坛徽章:
- 0
|
用Basic HTTP Authentication 保护起来的网页需要提供用户名与密码,否则就会出现401未授权的提示:
401 - Unauthorized
如果用python脚本进入这样的网页,除了需要知道用户名与密码以外,还需要知道该网页的realm。这个realm 在此网页的header 中带有 www-authenticate 字样的一行中。下面脚本用来判断401网页:
#!/usr/bin/python
import urllib2
import sys
url = 'http://ghostunix.org/'
# url = 'http://ftp.ubuntu.org.cn/home/ghosTM55/'
username = 'ubuntu'
password = 'ubuntuftp'
req = urllib2.Request(url)
try:
handle = urllib2.urlopen(req)
except IOError, e:
pass
else:
print "This page isn't protected by authentication."
sys.exit(1)
getrealm = e.headers['www-authenticate']
print getrealm
在上面的脚本中,我们拿出了两个范例网址,其中一个运行的结果是:
This page isn't protected by authentication.
这不是一个401网页,把上面的网址换成
http://ftp.ubuntu.org.cn/home/ghosTM55/
以后运行的结果是:
Basic realm="trac"
这是一个401网页,我们得到了它的 realm 值为 trac ,用下面的脚本登陆并打印这个被保护页面:
#!/usr/bin/python
import urllib2
auth = urllib2.HTTPBasicAuthHandler()
auth.add_password('trac', 'http://ftp.ubuntu.org.cn/home/ghosTM55/', 'ubuntu', 'ubuntuftp')
opener = urllib2.build_opener(auth, urllib2.CacheFTPHandler)
urllib2.install_opener(opener)
data = urllib2.urlopen('http://ftp.ubuntu.org.cn/home/ghosTM55/')
print data.read()
urllib2的资料:
http://python.org/doc/2.4.2/lib/urllib2-examples.html
[ 本帖最后由 mystérieux 于 2009-6-10 02:37 编辑 ] |
|