【发布时间】:2014-06-18 21:26:41
【问题描述】:
所以我编写了几个版本的代码,应该能够让我登录到需要身份验证的网页。 代码如下:
import urllib2
import sys
import re
import base64
from urlparse import urlparse
theurl = 'https://canvas.brown.edu/' #this is the real url
#a protected page - need to write the username and password below
username = 'username' #my username is here
password = 'XXXXXXXXX' #my password is here
print "Code begins"
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
#here we want to fail
print "Authentification error found"
pass
else:
#if we don't fail then the page isn't protected
print "This page isn't protected by authentication"
sys.exit(1)
if not hasattr(e, 'code') or e.code != 401:
#we got an error but not a 401 (need authentication) error
print "This page isn't protected by authentication"
print 'but we failed for another reason'
sys.exit(1)
authline = e.headers['www-authenticate']
#this gets www-athenticate from the headers
#which has the authentication scheme and realm in it
authobj = re.compile(
r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''', re.IGNORECASE)
#this regular expression is used to extract scheme and realm
matchobj = authobj.match(authline)
if not matchobj:
#if the authline isn't matched by the regular expression then something is wrong
print 'The authentication header is badly formed'
print authline
sys.exit(1)
scheme = matchobj.group(1)
realm = matchobj.group(2)
#here we've extracted the scheme and the realm from the header
if scheme.lower() != 'basic':
print 'This example only works with BASIC authentication'
sys.exit(1)
base64string = base64.encodestring(
'%s:%s'%(username, password))[:--1]
authheader = "Basic %s" %base64string
req.add_header("Authorization", authheader)
try:
handle = urllib2.urlopen(req)
except IOError, e:
#here we shouldn't fail if the username and password is right
print "It Looks like the username and password is wrong"
sys.exit(1)
thepage = handle.read()
print "It worked!"
我运行它然后我得到这个错误:
C:\Python27>python authen_example.py
Code begins
Authentification error found
This page isn't protected by authentication
but we failed for another reason
并且 1) 我知道我需要对此页面进行身份验证 2) 用来说服务器超时的错误 3)如果可能的话,我还希望我的代码提示我输入用户名和密码,而不是直接在代码中要求它
对于充满代码的帖子感到抱歉,但这已经困扰了我两个星期,但我仍然无处可去。 提前致谢。
【问题讨论】:
-
3)
username = raw_input("Username:") -
谢谢!这是让我感动的小事:)
标签: python url python-2.7 authentication