如何使用Python制作脚本巡检设备,并将结果输出到excel

本脚本使用了 pexpect 库来自动化 Telnet 登录到交换机并执行命令,然后将输出保存到文件中。

如果你想要将输出存储到 Excel 文件中,你可以使用 openpyxl 库来实现。

图片[1]-如何使用Python制作脚本巡检设备,并将结果输出到excel-不念博客

下面是一个将你提供的脚本与 Excel 输出结合的示例:

import pexpect
import sys
import datetime
import openpyxl

# 定义交换机信息和命令
switch_info = {
    "ip": "x.x.x.x",
    "passwd": "xxxx",
    "name": "<F5-Core-S12508>",
    "name1": "---- More ----"
}

# 创建 Excel 工作簿和工作表
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = "Switch Inspection"

child = pexpect.spawn('telnet %s' % switch_info["ip"])
child.expect('login:')
child.sendline("admin")
child.expect('(?i)ssword:')
child.sendline(switch_info["passwd"])
child.expect(switch_info["name"])

# 执行命令并将输出写入 Excel
def execute_command(command):
    child.sendline(command)
    child.expect(switch_info["name1"])
    result = child.before.decode("utf-8")
    return result

# 执行各个命令并写入 Excel
commands = [
    "display power",
    "display version",
    "display environment",
    "display fan",
    "display cpu-usage",
    "display memory",
    "display interface brief",
    "dis logbuffer",
    "display ip routing-table",
    "display irf link",
]
for command in commands:
    output = execute_command(command)
    worksheet.append([command, output])

child.sendline("quit")
child.expect(pexpect.EOF)

# 保存 Excel 文件
excel_filename = f"switch_inspection_{datetime.date.today().strftime('%Y%m%d')}.xlsx"
workbook.save(excel_filename)
print(f"Inspection results saved to {excel_filename}")

在这个示例中,我使用了 openpyxl 库来创建 Excel 工作簿和工作表,并在每次执行命令后将输出写入 Excel 表格中。

你可以根据实际需要进一步调整和优化这个脚本,确保交换机命令的执行和输出的写入都能符合你的要求。

同时,记得确保在运行脚本之前安装了所需的库:

pip install pexpect openpyxl

自动化与 Telnet 进行交互时,稳定性和错误处理非常重要,因为网络环境可能会导致意外情况。

© 版权声明
THE END
喜欢就支持一下吧
点赞109赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容