使用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
上一篇: 浏览器中的正则表达式陷阱说明
下一篇: 利用正则表达式提取固定字符之间的字符串