python实验11 JSON的应用

农村四月闲人少,勤学苦攻把名扬。这篇文章主要讲述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的应用】


    推荐阅读