将cli输出“show proc cpu history”解析为文件csv(使用TextFSM等)

2024-09-27 17:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有人知道如何读取这个表,并解析成CSV文件或其他东西。 我需要把它转换成图形(如果可能的话)。在

我真的很困惑怎么读这个表,不像'show inventory'或'show version'有一个TextFSM模板来解析数据,'show proc cpu history'有TextFSM模板什么的?在

显示进程cpu历史记录(来自show技术.txt)enter image description here


Tags: 文件csv数据模板图形历史记录进程version
1条回答
网友
1楼 · 发布于 2024-09-27 17:30:31

您需要读入文本文件并提取包含数值的每个图形上方的3行。这些需要“旋转”并转换成整数。在

下面的代码将读入文本文件并提取必要的行。它首先跳过所有的初始行,直到找到三个图的标题行。在

它旋转值(使用*zip(*data))。接下来,它根据源文件名将数据写出三个独立的CSV文件。在

最后,它使用Pythonmatplotlib库(需要安装)来显示三个图。在

from itertools import dropwhile, takewhile, izip_longest
import matplotlib.pyplot as plt
import csv
import re
import os
from collections import deque

def process_block(block):
    # Determine number of leading spaces (varies between files)
    start_offset = min(len(block[0]) - len(block[0].lstrip()), len(block[1]) - len(block[1].lstrip()))
    # Extract just data. Skip over leading spaces, remove trailing newline and replace any spaces with 0
    block = [line[start_offset:].rstrip('\n').replace(' ', '0') for line in block]
    # Convert to values
    return [int(''.join(entry)) for entry in zip(*block)]


def process_switch_file(figure, switch_filename):

    with open(switch_filename) as f_input:
        # Extract just the graph lines
        lines = list(takewhile(lambda x: "- show logging -" not in x, dropwhile(lambda x: "- show process cpu history -" not in x, f_input)))

    headings = ["CPU% per second (last 60 seconds)", "CPU% per minute (last 60 minutes)", "CPU% per hour (last 72 hours)"]

    # Keep reading each until a line starting 100 is found, keep the previous 2 lines
    data = []
    entry = iter(lines)

    while True:
        block = deque(takewhile(lambda x: not re.match(' *?100 ', x), entry), 2)

        if len(block[0]) <= 1:
            break
        data.append(block)

    data = [process_block(block) for block in data]
    x_values = [range(0, len(block)) for block in data]

    # Get the base filename (without path or extension)
    csv_filename = os.path.splitext(os.path.basename(switch_filename))[0]

    # Write data to a csv
    with open('{}_cpu_seconds.csv'.format(csv_filename), 'wb') as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow(['Second', 'Value'])
        csv_output.writerows(list(zip(x_values[0], data[0])))

    with open('{}_cpu_minutes.csv'.format(csv_filename), 'wb') as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow(['Minute', 'Value'])
        csv_output.writerows(list(zip(x_values[1], data[1])))

    with open('{}_cpu_hours.csv'.format(csv_filename), 'wb') as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow(['Hour', 'Value'])
        csv_output.writerows(list(zip(x_values[2], data[2])))

    fig = plt.figure(figure)
    fig.canvas.set_window_title(csv_filename)

    for subplot, x, block, heading in zip(range(311, 314), x_values, data, headings):
        # Display as graphs
        ax = fig.add_subplot(subplot)
        ax.set_xlabel(heading)
        ax.set_ylim(0, 100)
        plt.plot(x, block)

    plt.tight_layout()


for figure, filename in enumerate(['switch-2.txt', "switch-3.txt", "Switch.txt"], start=1):
    process_switch_file(figure, filename)

plt.show()

CSV文件将以如下方式启动:

^{pr2}$

显示屏将显示:

matplotlib graphs

matplotlib通常可以使用以下方式安装:

pip install matplotlib

相关问题 更多 >

    热门问题