利用Python进行性能测试(上)

Loadrunner虽好,但,它不是免费的,使用它就是行走在某种边缘;而且动不动就2G的安装包,实在难于下载和安装。

为何不用python实现一个性能测试的脚本呢?
从监控主机的CPU、内存、网络和磁盘开始,
到使用unittest的单元测试用例组建测试场景。
再到发起并发测试,获得监控数据;
最后生成性能表现图,从而分析应用的表现。
python都可以做到。
使用到了sar,iostat和脚本进行监控 。

#!/usr/bin/env python
# coding:utf-8
import paramiko
import urunite_test_py
import unittest
import numpy as np
import matplotlib.pyplot as plt
import pylab
import matplotlib.dates as mdates
from numpy import datetime64
from itertools import islice 
import re,os,time,shutil,logging
import threading
import datetime

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='parallel_test.log',
                filemode='w')

host1={"ip":"192.168.1.101",'port':22,"username":"app","passwd":"urpwd"}
host2={"ip":"192.1689.1.102",'port':22,"username":"app","passwd":"pwd"}
#将host添加到HOST中进行监控
HOST=[host1,host2]

data_path=os.path.join(os.getcwd(),"data")
pic_path=os.path.join(os.getcwd(),"picture")


#ssh,返回远程命令的输出结果。         
def ssh2(host,cmd):
    result=[]    
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        logging.info("connect to "+host['ip']+",user "+host['username']+",ssh")
        ssh.connect(host['ip'],int(host['port']),host['username'],host['passwd'],timeout=5)   
        for m in cmd:
            logging.info(m)
            stdin,stdout,stderr = ssh.exec_command(m)
            out = stdout.readlines()
            #return out
            for o in out:
                logging.info(o)
                result.append(o)
        ssh.close()
    except Exception,e:
        logging.DEBUG(e)
    return out    

#sftp,默认从对端home目录获取,放到本地当前目录
def sftpfile(host,getfiles,putfiles):
    try:
        logging.info("connnect to "+host['ip']+",user "+host['username']+",sftp")
        t=paramiko.Transport((host['ip'],int(host['port'])))
        t.connect(username=host['username'],password=host['passwd'])     
        sftp =paramiko.SFTPClient.from_transport(t)
        if getfiles<>None:
            for file in getfiles:
                logging.info("get "+file)
                file=file.replace("\n", "")
                sftp.get(file,file)
        if putfiles<>None:
            for file in putfiles:
                file=file.replace("\n", "")
                logging.info("put "+file)
                sftp.put(file,file)     
        t.close(); 
    except:     
        import traceback     
        traceback.print_exc()     
        try:         
            t.close()     
        except Exception,e:
            logging.DEBUG(e)

你可能感兴趣的:(pythonwalk)