本文参考了知乎专栏的两位大佬的文章,此Blog仅用于记录学习各种TextFSM模板的书写
朱嘉盛
弈心
参考阅读
网络工程师的Python之路–汇总
关于TextFSM的详细解读,点击如下URLTextFSM:强无敌的配置解析利器-全面解读
重点核心(正则内容)
正则如何匹配,不做过多赘述,再后续的数据整形中品味正则是如何使用的
tracert信息的TextFSM整形
模板文件位置:位于同级目录下template目录下的stracert.template
Value ID (\d+)
Value Hop (\S+)
Start
^ ${ID} ${Hop} +\d+ -> Record
标准格式写法注意事项:
- 变量声明后空一行;每一个变量就是一个rule
- Start顶头写且换行后至少空一格;^后面就是之前定义的rule
- 最后一个 -> Record代表识别到后把之前识别的都写入一条记录;箭头的左右侧必须有空格
def tracer(str1):
info = TextFSM(open('template\stracert.template')).ParseText(str1) # <class 'list'>
print(TextFSM(open('template\stracert.template')).header)
return info
str1 = '''
<R1>tracert 192.5.5.5
tracert 192.5.5.5
traceroute to 192.5.5.5(192.5.5.5), max hops: 30 ,packet length: 40,press CTRL_C to break
1 36.1.1.6 60 ms 50 ms 10 ms
2 67.1.1.7 100 ms 90 ms 80 ms
3 78.1.1.8 90 ms 80 ms 60 ms
4 59.1.1.9 100 ms 90 ms 80 ms
5 59.1.1.5 90 ms 100 ms 60 ms
'''
if __name__ == "__main__":
key = tracer(str1)
print(key)
执行:
['ID', 'Hop']
[['1', '36.1.1.6'], ['2', '67.1.1.7'], ['3', '78.1.1.8'], ['4', '59.1.1.9'], ['5', '59.1.1.5']]
可以看到,这样就将半结构化的string整形成了list,至此就可以随意提取任何想要的信息,比如此时我想要看第4跳到哪了?
if __name__ == "__main__":
key = tracer(str1)
print(key)
print(type(key))
print(key[3])
['ID', 'Hop']
[['1', '36.1.1.6'], ['2', '67.1.1.7'], ['3', '78.1.1.8'], ['4', '59.1.1.9'], ['5', '59.1.1.5']]
<class 'list'>
['4', '59.1.1.9']
若想要提取第4跳的IP就继续增加[]
if __name__ == "__main__":
key = tracer(str1)
print(key)
print(type(key))
print(key[3])
print(key[3][1])
['ID', 'Hop']
[['1', '36.1.1.6'], ['2', '67.1.1.7'], ['3', '78.1.1.8'], ['4', '59.1.1.9'], ['5', '59.1.1.5']]
<class 'list'>
['4', '59.1.1.9']
59.1.1.9
version信息的整形
模板内容
Value version (\d+.\d+\(\d+\)\w+\d+)
Value linux (\S+)
Value time (\d+\s+hours, \d+\s+minutes)
Value image (\S+)
Start
^\s+Version: Version\s+${version}
^\s+Linux Software\s+${linux}
^\s+Router uptime is\s+${time}
^\s+System image file is\s+${image} -> Record
def version(str):
info = TextFSM(open('template\sversion.template')).ParseTextToDicts(str) # <class 'list'>
print(TextFSM(open('template\sversion.template')).header)
return info
str2 = '''
Router#sho version
Cisco IOS Software
Linux Software (I86BI_LINUX-ADVENTERPRISEK9-M)
Version: Version 15.4(2)T4
DEVELOPMENT TEST SOFTWARE
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2015 by Cisco Systems, Inc.
Compiled Thu 08-Oct-15 21:21 by prod_rel_team
ROM: Bootstrap program is Linux
Router uptime is 14 hours, 41 minutes
System returned to ROM by reload at 0
System image file is "unix:/opt/unetlab/addons/iol/bin/L3_ADVENTERPRISEK9_M_15.4_2T.bin"
Last reload reason: Unknown reason
'''
if __name__ == "__main__":
key = version(str2)
print(key)
print(type(key))
执行结果:
['version', 'linux', 'time', 'image']
[{'version': '15.4(2)T4', 'linux': '(I86BI_LINUX-ADVENTERPRISEK9-M)', 'time': '14 hours, 41 minutes', 'image': '"unix:/opt/unetlab/addons/iol/bin/L3_ADVENTERPRISEK9_M_15.4_2T.bin"'}]
<class 'list'>