Jmeter7-Beanshell调用Python脚本实现ssh远程连接堡垒机,并跳转到目标主机执行shell指令

背景

最近在做性能测试的时候遇到了一个技术上的难点
HTTP请求的入参(check_data)是调用该接口时,后台调用内部接口请求移动端,移动端再调用第三方封装的so包返回参数给后台,以至于Jmeter通过寻常的方法没有办法获取。
后来想到,日志文件中会不会打印了check_data,果然,开发队友很给力,日志文件中有check_data
数据来源找到了,那么接下来的问题就是获取到check_data
日志文件所在的服务器需要先登录堡垒机才能连接到,两台服务器均为Linux

思路

我的思路是,jmeter通过Beanshell调用Python脚本实现ssh远程连接堡垒机,并跳转到目标主机执行shell指令

解决方案

1 Python脚本实现ssh远程连接堡垒机,并跳转到目标主机执行shell指令

之前使用过paramiko远程连接linux主机,想着用paramiko远程连接linux主机,然后再去连接目标机,然后从日志中截取包含check_data字符串的行,再用正则表达式获取check_data,应该就可以实现了。
实际上,思路是没错的,堡垒机本质上也是一个linux主机,ssh连接堡垒机也是OK的,但是连接上后,使用exec_command方法发送指令选择资源主机时,却总是返回No support the request method,“不支持请求方法”?
后来百度了一下,原来,堡垒机的界面不是普通shell交互界面,加了一层类似通道的东西。
正好,paramiko可以创建chanel连接

from paramiko.client import AutoAddPolicy
from paramiko.client import SSHClient
import time
import re
import sys


bsn=sys.argv[2]
try:
  ssh_client = SSHClient()
  ssh_client.set_missing_host_key_policy(AutoAddPolicy())
  ssh_client.connect(hostname='47.97.220.177', port=22, username='root', password='City_app123$', timeout=30)
  # 激活连接的终端
  channel = ssh_client.invoke_shell()
  # channel.get_pty()
  # 读、写操作超时时间,10秒
  channel.settimeout(10)

  try:
      channel.send("ssh 172.16.225.57" + '\n')
      time.sleep(2)
      command = 'cat /data/health-server/start.log | grep -A 2 "bsn=%s"' %bsn
      #print("command:%s" % command)
      channel.send(command + '\n')
      time.sleep(2)
      command_res = channel.recv(65533).decode('utf-8').strip()
      #print(command_res)
      channel.close()
  except Exception as e:
      print("在目标机(IP:%s)上读取数据操作超时")
  findCheakData = re.compile(r'checkData=(.*?), storeData=')
  cheak_data = re.findall(findCheakData, command_res)[0]
  #print(cheak_data)
  print('{}'.format(cheak_data))
except Exception as e:
  print(e)
2 Beanshell调用Python脚本

Jmeter7-Beanshell调用Python脚本实现ssh远程连接堡垒机,并跳转到目标主机执行shell指令_第1张图片

import java.io.BufferedReader;
import java.io.InputStreamReader;

String command="cmd /c python D://python_work//automation//ssh_connect.py -t ${bsn}";
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();
vars.put("check_data",response.toString()); //把结果赋值给变量 TEST ,方便后面调用

可以添加Debug Postprocessor查看check_data的返回值

你可能感兴趣的:(性能测试,python,jmeter)