欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用urllib进行HTTP验证

程序员文章站 2022-03-10 22:17:45
# HTTP验证 环境python3.8import urllib.request, urllib.error, urllib.parsefrom base64 import encodebytesLOGIN = 'wesley'PASSWD = "you'll guess"URL = 'http://loacalhost'REALM = 'Secure Archive'""" AuthType basic 已知域AuthName:Secure Archive Au...
# HTTP验证 环境python3.8
import urllib.request, urllib.error, urllib.parse
from base64 import encodebytes

LOGIN = 'wesley'
PASSWD = "you'll guess"
URL = 'http://loacalhost'
REALM = 'Secure Archive'
"""
    AuthType  basic
    已知域AuthName:Secure Archive
    AuthUserFile    /www/htdocs/.htpasswd
    require valid-user
"""


# handler方式
def handler_version(url):
    # 创建基本验证
    hdlr = urllib.request.HTTPBasicAuthHandler()
    # 加入验证信息
    hdlr.add_password(REALM, urllib.parse.urlparse(url)[1], LOGIN, PASSWD)
    # 基本的urlopen不支持验证,使用该法以扩展支持额外功能
    opener = urllib.request.build_opener(hdlr)
    urllib.request.install_opener(opener)
    return url


# request方式
def request_version(url):
    # 使用Requset便于加入报头信息
    req = urllib.request.Request(url)
    # 信息加密
    b64str = encodebytes(('%s:%s' % (LOGIN, PASSWD)).encode())[:-1]
    # 添加报头
    req.add_header("Authorization", "Basic %s" % b64str)
    return req


for funcType in ('handler', 'request'):
    print("***Using %s:" % funcType.upper())
    url = eval('%s_version' % funcType)(URL)
    f = urllib.request.urlopen(url)
    print(str(f.readlines()))
    f.close()

本文地址:https://blog.csdn.net/zhangge138/article/details/111881633

相关标签: python碎碎 python