jmeter使用base64验证码登录
依赖环境/工具:java环境、jmeter、python3、pycharm(ide工具)
此次主要操作步骤:
- 使用jmeter工具把验证码base64加密信息保存至本地。
- 编写python脚本(包含:解码bse64验证码图片、验证码图片背景降噪、对验证码图片文字识别、去除图片文字内空格、特殊字符并保存本地为txt文件)。
- jmeter内运行py文件,把打印内容变量给登录接口验证码字段。
1. 所有的操作、准备都基于2个接口【获取验证码、登录接口】执行。
- jmeter👉BeanShell后置处理程序
FileWriter fstream = new FileWriter("E:/test001/code.txt");//定义本地文件路径
BufferedWriter out = new BufferedWriter(fstream);
out.write("${image}");// 验证码base64变量名
out.write(System.getProperty("line.separator"));//换行
out.close();
fstream.close();
- jmeter👉BeanShell 取样器【执行py文件】
import java.io.BufferedReader;
import java.io.InputStreamReader;
String command = "cmd /c python E://D-drive-26093//pycharm//test01//venv//testA.py ";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
pr.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
StringBuilder response = new StringBuilder();
while ((line = b.readLine()) != null) {
response.append(line);
}
String response_data = response.toString();
System.out.println(response_data);
b.close();
//System.out.println(response.toString());
vars.put("code",response.toString()); //把结果赋值给变量 TEST ,方便后面调用
2.py文件
点击查看代码
from PIL import Image
import re
import pytesseract
import os, base64
import numpy as np
import time
import matplotlib.pyplot as plt
import ddddocr
# 对base64图片解码
with open("E:\\test001\\code.txt", "r") as f:
imgdata = base64.b64decode(f.read())
filea = open('E:\\test001\\1.jpg', 'wb')
filea.write(imgdata)
filea.close()
# 验证码降噪
image = Image.open('E:\\test001\\1.jpg','r')
image = image.convert('L')
image = np.asarray(image)
image = (image > 135) * 255
image = Image.fromarray(image).convert('RGB')
image.save('E:\\test001\\12345.jpg')
time.sleep(2)
# 识别验证码图片文字
ocr = ddddocr.DdddOcr()
with open('E:\\test001\\12345.jpg', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
file = open('E:\\test001\\001test.txt', mode='w')
file.writelines(res)
print (res)