python 基本认证

# import requests
#
# response = requests.get('http://127.0.0.1:8080/manager/html', auth=('tomcat', 'tomcat'))
# print(response.content.decode())
import base64
import re
import urllib.request
from urllib.error import HTTPError


class BasicAuth(object):

    def __init__(self, username, password, realm=''):
        auth_str = f"{username}:{password}"
        encode = base64.standard_b64encode(auth_str.encode()).decode()
        auth_str = f'Basic {encode}'
        self.auth = auth_str
        self.realm = realm

    def open(self, url):
        request = urllib.request.Request(url)
        try:
            response = urllib.request.urlopen(request)
            return response
        except HTTPError as e:
            auth_type = e.headers['www-authenticate']
            auth_str = re.compile(
                '(?P<schema>\w*)\s*realm=[\'"](?P<realm>[^\'"]*)[\'"]',
                re.IGNORECASE)
            match_ = auth_str.match(auth_type)
            if match_:
                match = match_.groupdict()
                schema = match.get('schema')
                if schema.lower() == 'basic':
                    request.add_header("Authorization", self.auth)
                    try:
                        response = urllib.request.urlopen(request)
                        print(response.read().decode())
                        return response
                    except HTTPError as e:
                        print(e.headers)


# base = BasicAuth('tomcat', 'tomcat')
# base.open('http://127.0.0.1:8080/manager/html')


basic_auth = urllib.request.HTTPPasswordMgrWithDefaultRealm()
basic_auth.add_password(None, 'http://127.0.0.1:8080/manager/html', 'tomcat', 'tomcat')
handler = urllib.request.HTTPBasicAuthHandler(basic_auth)
opener = urllib.request.build_opener(handler)
urllib.request.install_opener(opener)
response = urllib.request.urlopen('http://127.0.0.1:8080/manager/html')
print(response.read().decode())

posted @ 2018-12-09 14:33  曾春云  阅读(819)  评论(0编辑  收藏  举报