python实验11 JSON的应用
Posted 睡着的冰淇淋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实验11 JSON的应用相关的知识,希望对你有一定的参考价值。
本节实验详细可参考
python 第三方库中有关 JOSN 的详解(Linux下):https://blog.51cto.com/u_15450494/5208225
实验运行环境
实验目的
之前,我们⽤正则表达式来寻找哪些物理接⼝是up的,但如果如今的需求改为,寻找出来哪些端⼝是up的(包括vlanif端⼝),并且还要给出他们的端⼝号和IP地址,这时候正则表达式就显得⼼有余⽽⼒不⾜了。
TextFSM是Google开发的⼀个开源python库,他能让⽤户⾃定义设计出⼀套规则,然后⽤该规则来处理⽂本内容,将⽆规律的⽂本内容按照我们想要的格式变成有规律的数据格式。因此我们可以使⽤TextFSM来将show ip int br的回显内容转换成JSON格式,然后使⽤for循环来找出我们想要的东⻄。
转换成JSON格式后回显是这样的:
[
"intf": "GigabitEthernet0/0",
"ipaddr": "unassigned",
"status": "up",
"proto": "up"
,
"intf": "GigabitEthernet0/1",
"ipaddr": "unassigned",
"status": "down",
"proto": "down"
,
"intf": "GigabitEthernet0/2",
"ipaddr": "unassigned",
"status": "down",
"proto": "down"
,
"intf": "GigabitEthernet0/3",
"ipaddr": "unassigned",
"status": "down",
"proto": "down"
,
]
好消息是,已经有⼈提前⽤TextFSM写好了这样的需求的模板,ntc-templates,⽀持多家⼚商的绝⼤多数的show display命令的回显转为JSON格式。
实验准备
在 Windows 下运行本实验时,也需要安装 ntc-templates:
1. 安装Git(百度)
2. Cmd 输⼊:git clone git://github.com/networktocode/ntc-templates.git
3. 检查python模块中是否成功安装ntc-templates
实验脚本
寻找SW1的up接⼝,和这些接⼝的IP,状态。
import json
SW1=
"device_type": "cisco_ios",
"ip":192.168.2.11,
"username": "python",
"password": "123",
connet=ConnectHandler(**SW1)
print("Successfully connected to "+SW1[ip])
interfaces=connet.send_command(show ip int br,use_textfsm=True) #确定使用TestFSM来转换数据格式
print(json.dumps(interfaces,indent=2)) #indent参数表示在每个对象的键值对前有几个空格,为了更美观的输出
for interface in interfaces:
if interface["status"]==up:
print(finterface["intf"] is up! IP address: interface["ipaddr"])
以上是关于python实验11 JSON的应用的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Python 中的 websocket 消息增量解析 JSON?
python之路day11RabbitMQRedisMysql
在 Python 中使用 Spark Streaming 解析 JSON 消息