python有认证考试吗_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\w*)\s*realm=[\'"](?P[^\'"]*)[\'"]',

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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值