python 压测 +paramiko 远程监下载日志 +js 测试报告

news2025/4/16 12:42:56

目录

前言:

关于压测客户端

netty nio 压测端

python tornado 异步框架压测

python 协程压测端

远程监控

js 解析日志


前言:

在软件开发中,压测和测试是非常重要的一个环节,它可以帮助我们更加全面地检测软件中的安全漏洞和风险。paramiko 是 Python 中的一个模块,可以帮助我们通过 SSH 协议进行远程登录和操作。JavaScript 是一种常用的脚本语言,可以帮助我们更加方便地进行网页测试和监控。

关于压测客户端

netty nio 压测端

package com.nio.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpVersion;
import java.net.URI;
import java.nio.charset.StandardCharsets;
public class HttpClient {
    public void connect(String host, int port) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                    ch.pipeline().addLast(new HttpResponseDecoder());
                    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
                    ch.pipeline().addLast(new HttpRequestEncoder());
                    ch.pipeline().addLast(new HttpClientInboundHandler()); 
                }
            });
                 ChannelFuture f = b.connect(host, port).sync();

               URI uri = new URI("http://gc.ditu.aliyun.com:80/geocoding?a=深圳市");
                 String msg = "Are you ok?";
                 DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                         uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));                             
                 // 构建http请求
                 request.headers().set(HttpHeaders.Names.HOST, host);
                 request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                 request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
                 // 发送http请求
                 f.channel().write(request);
                 f.channel().flush();
                 f.channel().closeFuture().sync();                
//            }

        } finally {
            workerGroup.shutdownGracefully();
        }
    }
    public void connect_post(String host, int port) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                    ch.pipeline().addLast(new HttpResponseDecoder());
                    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
                    ch.pipeline().addLast(new HttpRequestEncoder());
                    ch.pipeline().addLast(new HttpClientInboundHandler()); 
                }
            });

                 ChannelFuture f = b.connect(host, port).sync();

               URI uri = new URI("http://gc.ditu.aliyun.com:80/geocoding?a=深圳市");
               FullHttpRequest request = new DefaultFullHttpRequest(
                       HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath());                        
                 // 构建http请求
               request.headers().set(HttpHeaders.Names.HOST, host);
               request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // or HttpHeaders.Values.CLOSE
               request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
               request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");
               ByteBuf bbuf = Unpooled.copiedBuffer("{\"jsonrpc\":\"2.0\",\"method\":\"calc.add\",\"params\":[1,2],\"id\":1}", StandardCharsets.UTF_8);
               request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bbuf.readableBytes());
                 // 发送http请求
                 f.channel().write(request);
                 f.channel().flush();
                 f.channel().closeFuture().sync();

//            }

        } finally {
            workerGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
            //请自行修改成服务端的IP
        for(int k=0; k<1;k++){
          client.connect("http://gc.ditu.aliyun.com/", 80);

            System.out.println(k);
            }
    }
}
监听代码
package com.nio.test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.print("success!~!~");
        if (msg instanceof HttpResponse) 
        {
            HttpResponse response = (HttpResponse) msg;
//            System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
            System.out.println("HTTP_CODE:" + response.getStatus());

        }
        if(msg instanceof HttpContent)
        {
            HttpContent content = (HttpContent)msg;
            ByteBuf buf = content.content();

            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();
        }
        ctx.close();
    }
}

python tornado 异步框架压测

import tornado.ioloop
from tornado.httpclient import AsyncHTTPClient
def handle_request(response):
  if response.error:
      print ("Error:", response.error)
  else:
      print(response.body)
param = {"msg":"111"}
param["img_msg"] = open("t.jpg",'r',encoding='utf-8')
url = 'http://gc.ditu.aliyun.com/geocoding?a=苏州市'
i = 1
print(param)
req = tornado.httpclient.HTTPRequest(url, 'POST', body=str(param))
http_client = AsyncHTTPClient()
while i<10000:
  i += 1
  http_client.fetch(req, handle_request)
tornado.ioloop.IOLoop.instance().start()

python 协程压测端

#-*- coding: utf-8 -*-
import urllib.request
# url = "http://r.qzone.qq.com/cgi-bin/user/cgi_personal_card?uin=284772894"
url = "http://gc.ditu.aliyun.com/geocoding?a="+urllib.request.quote("苏州市")
HEADER = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0'}

# 自定义请求的方法,get post
def f(url):
    import urllib
    import urllib.request
    data=urllib.request.urlopen(url).read()
    z_data=data.decode('UTF-8')
    print(z_data)

# 我自己封装了gevent 的方法,重载了run
from gevent import Greenlet
class MyGreenlet(Greenlet):
    def __init__(self, func):
        Greenlet.__init__(self)
        self.func = func
    def _run(self):
        # gevent.sleep(self.n)
        self.func


count = 3
green_let = []
for i in range(0, count):
    green_let.append(MyGreenlet(f(url)))
for j in range(0, count):
    green_let[j].start()
for k in range(0, count):
    green_let[k].join()
  • 当然也可以用多线程,apache ab 等,如果是大量并发可以使用 netty nio 压测 + 虚拟机的方式(其实原理差不多,协程,tornado 等)

远程监控

  • 把此 shell 脚本上传到服务器

    #!/bin/bash
    if (( $# != 1))
    then
    echo "please input sum times:"
    exit 1
    fi
    sar -u 1 $1 | sed '1,3d'|sed '$d' > sar_cpu_1.txt
    sar -r 1 $1 |sed '1,3d'|sed '$d' > sar_men_1.txt
    sar -b 1 $1 |sed '1,3d'|sed '$d' > sar_io_1.txt
    
  • 远程上传 shell 脚本,执行,下载日志

import paramiko
import paramiko
server_ip = '192.168.1.1'
server_user = 'root'
server_passwd = ''
server_port = 22
ssh = paramiko.SSHClient()
def ssh_connect():
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    ssh.connect(server_ip, server_port,server_user, server_passwd)
    return ssh
def client_connect():
    client = paramiko.Transport((server_ip, server_port))
    client.connect(username = server_user, password = server_passwd)
    return client
def ssh_disconnect(client):
    client.close()

def exec_cmd(command, ssh):
    '''
    windows客户端远程执行linux服务器上命令
    '''
    stdin, stdout, stderr = ssh.exec_command(command)
    err = stderr.readline()
    out = stdout.readline()
    print(stdout.read())

def win_to_linux(localpath, remotepath,client):
    '''
    windows向linux服务器上传文件.
    localpath  为本地文件的绝对路径。如:D:  est.py
    remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt
    '''

    sftp = paramiko.SFTPClient.from_transport(client)
    sftp.put(localpath,remotepath)
    client.close()

def linux_to_win(localpath, remotepath,client):
    '''
    从linux服务器下载文件到本地
    localpath  为本地文件的绝对路径。如:D:  est.py
    remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt
    '''
    sftp = paramiko.SFTPClient.from_transport(client)
    sftp.get(remotepath, localpath)
    client.close()

class AllowAllKeys(paramiko.MissingHostKeyPolicy):
   def missing_host_key(self, client, hostname, key):
       return

def muit_exec_cmd(ssh,cmd):
    '''
    ssh ssh连接
    cmd 多命名
    '''
    ssh.set_missing_host_key_policy(AllowAllKeys())
    channel = ssh.invoke_shell()
    stdin = channel.makefile('wb')
    stdout = channel.makefile('rb')

    stdin.write(cmd)
    print(stdout.read())

    stdout.close()
    stdin.close()

cl = client_connect()
sh = ssh_connect()
win_to_linux("get_men_cpu.sh","/data/get_men_cpu.sh",cl)
exec_cmd("/data/get_men_cpu.sh 100",sh)
# 要和服务器那边的监控时间结束同步,可以设置下sleep时间
linux_to_win("d:/cpu.txt","/data/sar_cpu_1.txt",cl)
linux_to_win("d:/men.txt","/data/sar_men_1.txt",cl)
linux_to_win("d:/io.txt","/data/sar_io_1.txt",cl)
cl.close()
sh.close()

js 解析日志

  • js 分析日志文件.cpu,内存,io 都是基于这样分析 用的 highcharts 插件,自己去学习吧
<script>
    var idle= [];
    var iowait = [];
    var categories = [];
    var temp;
    $(function () {
        $.get( "txt/sar_cpu.txt", function( data ) {
            var resourceContent = data.toString(); // can be a global variable too...
            var rc = resourceContent.split("\n");
            for(var i=0; i<rc.length; i++){
             temp = getNotNullArr(rc[i].split(" "));
                console.log(temp);
                idle.push(parseFloat(temp[temp.length-1]));
                categories.push(temp[0]);
                iowait.push(parseFloat(temp[6]));
            }
            set_h_title("cpu使用情况");
            set_h_sub_title("test.com");
            set_h_xaxis_setp(1);
            set_h_tooltip("%");
            set_h_yaxis_title("cpu使用情况");
            set_h_xaxis_categories(categories);
            set_h_series( [{name: 'idle',data:idle}, {name: 'iowait', data: iowait}]);
            highchartsinit("#container",get_h_title(),get_h_sub_title(),get_h_xaxis_setp(),get_h_xaxis_categories(),get_h_yaxis_title(),get_h_tooltip(),get_h_series());
    });
    });
</script>

Paste_Image.png

Paste_Image.png

Paste_Image.png

  作为一位过来人也是希望大家少走一些弯路

在这里我给大家分享一些自动化测试前进之路的必须品,希望能对你带来帮助。

(软件测试相关资料,自动化测试相关资料,技术问题答疑等等)

相信能使你更好的进步!

点击下方小卡片

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/785293.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SR04 超声波测距模块

文章目录 前言一、SR04 模块介绍二、设备树设置三、驱动程序四、测试程序五、上级测试及效果总结 前言 超声波测距模块 是利用超声波来测距。模块先发送超声波&#xff0c;然后接收反射回来的超声波&#xff0c;由反射经历的时间和声音的传播速度 340m/s&#xff0c;计算得出距…

剑指offer40.最小的k个数

简直不要太简单了这道题&#xff0c;先给数组排个序&#xff0c;然后输出前k个数就好了。我用的是快排&#xff0c;这是我的代码&#xff1a; class Solution {public int[] getLeastNumbers(int[] arr, int k) {int n arr.length;quickSort(arr, 0, n-1);int[] res new int…

Mysql 简介

Mysql 简介 学习目的 MySQL作为目前最流行的关系型数据库管理系统之一&#xff0c;因其开源免费的特性&#xff0c;成为小型Web应用的重点关注对象。几乎所有的动态Web应用基本都在使用MySQL作为数据管理系统。学习MySQL的目的也是为了更好地理解数据库相关的SQL注入漏洞&…

【性能优化】MySQL百万数据深度分页优化思路分析

业务场景 一般在项目开发中会有很多的统计数据需要进行上报分析&#xff0c;一般在分析过后会在后台展示出来给运营和产品进行分页查看&#xff0c;最常见的一种就是根据日期进行筛选。这种统计数据随着时间的推移数据量会慢慢的变大&#xff0c;达到百万、千万条数据只是时间问…

关于脑电睡眠分期,你应该知道的还有这些

导读 基于电生理信号(EEG&#xff0c;EOG和EMG)对睡眠阶段进行识别的建议源自Rechtschaffen和Kales手册&#xff0c;由美国睡眠医学学会于2007年发布&#xff0c;并定期更新多年。这些建议对于评估不同类型的睡眠/觉醒主观评定中的客观标志物非常重要。凭借研究的简单、可重复…

windows/linux/mac上编译open3d 0.17.0

目录 写在前面准备编译windows:linux/mac:注&#xff1a; 参考完 写在前面 1、本文内容 windows/linux/mac上编译open3d 0.17.0 2、平台 通过cmake构建项目&#xff0c;跨平台通用 3、转载请注明出处&#xff1a; https://blog.csdn.net/qq_41102371/article/details/1318918…

基于C++的QT基础教程学习笔记

文章目录&#xff1a; 来源 教程社区 一&#xff1a;QT下载安装 二&#xff1a;注意事项 1.在哪里写程序 2.如何看手册 3.技巧 三&#xff1a;常用函数 1.窗口 2.相关 3.按钮 4.信号与槽函数 5.常用栏 菜单栏 工具栏 状态栏 6.铆接部件 7.文本编辑 8…

[ELK安装篇]:基于Docker虚拟容器化(主要LogStash)

文章目录 一&#xff1a;前置准备-(参考之前博客)&#xff1a;1.1&#xff1a;准备Elasticsearch和Kibana环境&#xff1a;1.1.1&#xff1a;地址&#xff1a;https://blog.csdn.net/Abraxs/article/details/128517777 二&#xff1a;Docker安装LogStash(数据收集引擎&#xff…

SH-FAPI-4,新型tumor显像剂,其中FAPI通过与FAP结合

资料编辑|陕西新研博美生物科技有限公司小编MISSwu​ SH-FAPI-4 其中FAPI通过与FAP结合&#xff0c;可在PET-CT扫描中可视化tumor的位置和大小&#xff0c;从而帮助确定tumor的类型和位置&#xff0c;并指导tumor treatment的选择。FAPI被认为是一种具有潜在应用前景的新型tu…

vue检测数据变化的原理

vue监测数据变化的原理 vue会监视data中所有层次的数据。 监测对象类型的数据 原理 vue监测对象类型的数据通过setter实现&#xff0c;且要在new Vue时就传入要监测的数据。 对象中后追加的属性&#xff0c;Vue默认不做响应式处理&#xff1b;如需后续添加的属性做响应式&am…

吉林大学计算机软件考研经验贴

文章目录 简介政治英语数学专业课 简介 本人23考研&#xff0c;一战上岸吉林大学软件工程专硕&#xff0c;政治72分&#xff0c;英一71分&#xff0c;数二144分&#xff0c;专业课967综合146分&#xff0c;总分433分&#xff0c;上图&#xff1a; 如果学弟学妹需要专业课资料…

STM32MP157驱动开发——按键驱动(定时器)

“定时器 ”机制&#xff1a; 内核函数 定时器涉及函数参考内核源码&#xff1a;include\linux\timer.h 给定时器的各个参数赋值&#xff1a; setup_timer(struct timer_list * timer, void (*function)(unsigned long),unsigned long data)&#xff1a;设置定时器&#xf…

HALCON error #5504 Image too large for this HALCON version in operator问题解决

目录&#xff1a; 一&#xff0c;问题概述&#xff1a;二&#xff0c;解决方法 一&#xff0c;问题概述&#xff1a; &#x1f300;当你直接或间接使用Halcon来做图像读取的时候&#xff0c;你可能遇到5504错误&#xff1a;HalconDotNet.HOperatorException:HALCON error #5504…

传奇开区网站打开跳转到别的网站处理教程

打开跳转被劫持到其他网站如何处理教程。 在解决劫持之前&#xff0c;需要先确定一下身份&#xff0c;如果是网站被劫持了&#xff0c;或者是访客访问自己的网站被劫持到其他的网站上&#xff0c;解决起来的方法不一样&#xff0c;下面一休分类分享给大家 1、访客身份处理方法…

opencv-19 图像色彩空间转换函数cv2.cvtColor()

cv2.cvtColor() 函数是 OpenCV 中用于图像颜色空间转换的函数。它允许你将图像从一个色彩空间转换为另一个色彩空间。在 Python 中&#xff0c;你可以使用这个函数来实现不同色彩空间之间的转换。 函数的基本语法为&#xff1a; cv2.cvtColor(src, code[, dst[, dstCn]])参数…

提高可视性的五大方法可增强 Horizon Cloud 下一代平台的性能和用户体验

我们在 VMware Explore US 2022 推出了 VMware Horizon Cloud 下一代平台。该平台为使用现代化虚拟桌面和应用的客户提供了一个新的混合型桌面服务&#xff08;DaaS&#xff09;架构&#xff0c;其围绕降低成本和提高可扩展性而构建。首次发布后&#xff0c;我们在 VMware Expl…

Java | 数组排序算法

一、冒泡排序 冒泡排序的基本思想是对比相邻的元素值&#xff0c;如果满足条件就交换元素值&#xff0c;把较小的元素移到数组前面&#xff0c;把较大的元素移到数组后面&#xff08;也就是交换两个元素的位置&#xff09;&#xff0c;这样较小的元素就像气泡一样从底部升到顶…

Python2、python3的安装

目录 一、环境搭建和简单命令 1. 关于交互模式 2.执行文件 3. print 4. 安装/卸载包 5. 查看安装了哪些包 6. 升级pip本身 7. 查看包的具体信息 8. 搜索含有nose 9. 所有包升级到最新版本 二、其他说明 1. –m的使用 2. 切换盘符 资料获取方法 一、环境搭建和简单…

vue3 项目打包后白屏

根据Vue3.x文档&#xff0c;在 vue.config.js/vite.config.ts 统一对webpack、跨域、端口号等属性进行配置。 1.在 vue.config.js/vite.config.ts添加publicPath属性并将值更改成 ‘./’ 在这里插入图片描述 2.若还没有解决就去路由中将history模式设置成默认的Hash模式&…

MATLAB与ROS联合仿真——Simulink生成ROS代码

当我们用simulink完成控制程序的搭建后&#xff0c;我们期望下一次可以直接对ROS进行控制&#xff0c;而不是每次都需要启动matlab和simulink&#xff0c;因此我们可以使用simulink的代码生成器&#xff0c;生成ROS代码 1、生成代码前需要进行如下的设置 &#xff08;1&#xf…