讨鬼传迅御魂:利用 vmstat+gnuplot+python脚本生成CPU和内存使用率图表

来源:百度文库 编辑:偶看新闻 时间:2024/04/30 02:23:33

最近接触了 gnuplot 这个不错的工具,虽然生成图表的功能可以通过 excel 容易的实现,但是在 linux 命令行下可以跟其他工具配合,轻松实现”自动化”。vmstat 可以不断的显示 linux 系统的 CPU/内存以及 io 的使用情况: vmstat 2 1000 表示每俩秒显示一次系统各种资源消耗情况,一共执行 1000 次。于是做了个比较简单丑陋的 python 脚本,格式化 vmstat 的输出数据并利用 gnuplot 生成图表—脚本中实际上是调用测试 web server 压力的工具 autobench 对 gnuplot 的一个再封装脚本 bench2png,生成完以后用 sz 命令下载到本地,然后删除服务器上的文件。gnuplot 的用法后面再整理下 。

#!/usr/bin/python
# -*- coding: utf-8 -*-
# 处理规则: 目录下文件名包含 vmstat 的 .txt 或者 .log 后缀文件,
 
# 导入正则
import re
# 字符操作
import string
# 调用系统命令
import os
import sys
 
# 确认目录
path = r'./'
if path[-1:] != '/':
    path = path + '/'
 
### 遍历当前目录下的文件
 
fileList = os.listdir(path)
for file in fileList:
    # 文件名中没有 vmstat 则不处理
    if file.find('vmstat') < 0:
        continue;
    # 只处理后缀 .txt 或者 .log 的文件
    if file[-4:] != '.txt' and file[-4:] != '.log':
        continue
    # 如果对应的 tsv 文件不存在, 则生成
    tsvFile = file[0:-4] + '.tsv'
    if not os.path.exists(path + tsvFile):
        fileHandle = open(path + file);
        # 生成 tsv 文件
        fileContent = ''
        i = 0
        header = ''
        for line in fileHandle.readlines():
        # 保证每行开始都一样:至少有一个空格
        line = ' ' + line
            # 如果该行存在 procs 则不处理
            if line.find('procs') > -1:
                continue
            # 前 10 行出现 cache 字符表明是列说明,则保留
            if line.find('cache') > -1 and i > 10:
                continue
            # 替换字符
            line = re.sub(r"\n +", "\n", line) # 替换各种换行回车为 \n ,并去掉行尾空格
            line = re.sub(r" +", "\t", line) # 替换连续空格为 tab
            # 加一列数字
            fileContent += str(i) + line
            i = i + 1
        # 写入 tsv 文件
        tsvFileHandle = open(path + tsvFile, 'w')
        tsvFileHandle.write(fileContent)
        tsvFileHandle.close()
        # 关闭原文件
        fileHandle.close()
 
    # 如果对应 png 文件没有生成,则生成
    memPngFile = file[0:-4] + '.mem.png'
    cpuPngFile = file[0:-4] + '.cpu.png'
    if not os.path.exists(path + memPngFile):
        os.system("bench2png " + path + tsvFile + " " + path+ memPngFile + " 4 5 6 7 <        os.system("bench2png " + path + tsvFile + " " + path+ cpuPngFile + " 14 15 16 17 <    # 下载并删除
    os.system("sz " + path + file[0:-4] + "*")
    os.system("rm " + path + file[0:-4] + "*")
sys.exit()

有一个值得改进的机制就是最好能够通过 python 脚本内部调用 vmstat 而不是去分析 vmstat 的输出结果,不过作为我第二个实用 python 脚本,感觉还是不错了 :) 下面是生成图效果:

One Response to “利用 vmstat+gnuplot+python脚本生成CPU和内存使用率图表”