Advertisement
Guest User

Untitled

a guest
May 23rd, 2016
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. mport urllib2
  2. import sys
  3. import re
  4. import base64
  5. from urlparse import urlparse
  6.  
  7. theurl = 'http://www.someserver.com/somepath/somepage.html'
  8. # if you want to run this example you'll need to supply
  9. # a protected page with your username and password
  10.  
  11. username = 'johnny'
  12. password = 'XXXXXX' # a very bad password
  13.  
  14. req = urllib2.Request(theurl)
  15. try:
  16. handle = urllib2.urlopen(req)
  17. except IOError, e:
  18. # here we *want* to fail
  19. pass
  20. else:
  21. # If we don't fail then the page isn't protected
  22. print "This page isn't protected by authentication."
  23. sys.exit(1)
  24.  
  25. if not hasattr(e, 'code') or e.code != 401:
  26. # we got an error - but not a 401 error
  27. print "This page isn't protected by authentication."
  28. print 'But we failed for another reason.'
  29. sys.exit(1)
  30.  
  31. authline = e.headers['www-authenticate']
  32. # this gets the www-authenticate line from the headers
  33. # which has the authentication scheme and realm in it
  34.  
  35.  
  36. authobj = re.compile(
  37. r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',
  38. re.IGNORECASE)
  39. # this regular expression is used to extract scheme and realm
  40. matchobj = authobj.match(authline)
  41.  
  42. if not matchobj:
  43. # if the authline isn't matched by the regular expression
  44. # then something is wrong
  45. print 'The authentication header is badly formed.'
  46. print authline
  47. sys.exit(1)
  48.  
  49. scheme = matchobj.group(1)
  50. realm = matchobj.group(2)
  51. # here we've extracted the scheme
  52. # and the realm from the header
  53. if scheme.lower() != 'basic':
  54. print 'This example only works with BASIC authentication.'
  55. sys.exit(1)
  56.  
  57. base64string = base64.encodestring(
  58. '%s:%s' % (username, password))[:-1]
  59. authheader = "Basic %s" % base64string
  60. req.add_header("Authorization", authheader)
  61. try:
  62. handle = urllib2.urlopen(req)
  63. except IOError, e:
  64. # here we shouldn't fail if the username/password is right
  65. print "It looks like the username or password is wrong."
  66. sys.exit(1)
  67. thepage = handle.read()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement