python ntc-templates 中增加自定义模板

python ntc-templates 中增加自定义模板

原创内容,转载请注明出处。


可以复制现有的模板,如华为的huawei_vrp_display_version.textfsm模板复制为华三的hp_comware_display_version.textfsm


原模板内容:

Value VRP_VERSION (\S+)
Value PRODUCT_VERSION (.+)
Value MODEL (.+)
Value UPTIME (.+)


Start
  ^.*software,\s+Version\s+${VRP_VERSION}\s+\(${PRODUCT_VERSION}\)
  ^HUAWEI\s+${MODEL}\s+uptime\s+is\s+${UPTIME}$$

复制为 hp_comware_display_version.textfsm,并修改模板内容为:

Value VRP_VERSION (.+)
Value PRODUCT_VERSION (.+)
Value MODEL (.+)
Value UPTIME (.+)
Value Reboot_Reason (.+)


Start
  ^.*(S|s)oftware,\s+Version\s+${VRP_VERSION},\s+${PRODUCT_VERSION}
  ^H3C\s+${MODEL}\s+uptime\s+is\s+${UPTIME}
  ^Last (r|R)eboot (r|R)eason:\s+${Reboot_Reason}$$
  • 最后一行增加了上次重启的原因;
  • (S|s):匹配S或s;

还要在ntc-templates目录下的index文件中增加模板对应的命令,才能匹配上:

hp_comware_display_version.textfsm, .*, hp_comware, di[[splay]] ve[[rsion]]

要匹配的文本内容大概是这样:

<S2>dis version
H3C Comware Software, Version 7.1.075, Alpha 7571
Copyright (c) 2004-2017 New H3C Technologies Co., Ltd. All rights reserved.
H3C S5820V2-54QS-GE uptime is 0 weeks, 0 days, 0 hours, 0 minutes
Last reboot reason: User reboot
Boot image: flash:/s5820v2_5830v2-cmw710-boot-a7514.bin
Boot image version: 7.1.075, Alpha 7571
  Compiled Sep 20 2017 16:00:00
Boot image: flash:/s5820v2_5830v2-cmw710-system-a7514.bin
Boot image version: 7.1.075, Alpha 7571
  Compiled Sep 20 2017 16:00:00


匹配效果如下:

成功连接到设备 192.168.56.11
[
  {
    "vrp_version": "7.1.075",
    "product_version": "Alpha 7571",
    "model": "S5820V2-54QS-GE",
    "uptime": "0 weeks, 0 days, 2 hours, 43 minutes",
    "reboot_reason": "User reboot"
  }
]

脚本内容:

#!/usr/bin/python3
from netmiko import ConnectHandler
import json
import os

print(os.path.dirname(__file__))			#获取当前py文件的路径。
os.chdir(os.path.dirname(__file__))			#将当前py文件路径设置为工作路径。

with open('../ip.txt','r') as ipList:
    for line in ipList.readlines():
        fLine=line.strip()
        SW2={
            'device_type': fLine.split('---')[3],
            'ip': fLine.split('---')[0],
            'username': fLine.split('---')[1],
            'password': fLine.split('---')[2]
        }

        connect = ConnectHandler(**SW2)
        print('成功连接到设备 '+SW2['ip'])
        version = connect.send_command('disp version', use_textfsm=True)
        print(json.dumps(version, indent=2))

ip.txt 文件的内容为:

点击查看代码
192.168.56.11---admin---123456---hp_comware
192.168.56.12---admin---123456---hp_comware
192.168.56.13---admin---123456---hp_comware
192.168.56.14---admin---123456---hp_comware
192.168.56.15---admin---123456---hp_comware
192.168.56.11---admin---123456---hp_comware
192.168.56.57---admin---123456---hp_comware
192.168.56.58---admin---123456---hp_comware

posted @ 2021-10-28 21:44  飞飞6779  阅读(462)  评论(0编辑  收藏  举报