我是脚本新手,所以任何帮助都会走很长一段路,
它更多与Cisco路由器配置文件有关,第一种格式是当您运行命令“ show running-config”时,第二部分是当您使用命令“ show running-configformal”时
因此,我想将配置txt文件转换为更高格式。
我的Linux操作系统中有一个文件,其中包含以下数据,
control-plane
management-plane
inband
interface all
allow xy
address x.x.x.x
address y.y.y.y
!
allow b
address b.b.b.b
!
!
!
我想要的是删除其格式,因此基本上可以使用linux命令或使用python脚本将子节附加到父级。您认为最好的方法是什么?
control-plane management-plane inband interface all allow xy
control-plane management-plane inband interface all allow xy address x.x.x.x
control-plane management-plane inband interface all allow xy address y.y.y.y
control-plane management-plane inband interface all allow b
control-plane management-plane inband interface all allow b address b.b.b.b
使用相同的概念,我想在同一文件中进一步重新格式化
service sesh instance1
service-location preferred-active 0/3/CPU0
service-type nps nps-1
forced-placement npu 0
tunnel type gre
name gre10
tunnel-destination ipv4 address 209.165.200.225
ipv4 address 192.0.2.6/24
remote ipv4 address 192.0.2.5/24
tunnel-source ipv4 address 209.165.200.226
!
package nps-mips64-r2.rpm
interface ServiceApp1
remote ipv4 address 209.165.200.227/24
!
!
!
template pre-pos
interface preconfigure POS0/1/0/0
ipv4 address 10.3.32.154 255.0.0.0
!
我也附上了an image,目的只是为了让图片更清晰。
谢谢
萨尔
答案 0 :(得分:1)
希望这可以帮助您
file = open('text.txt','r')
allow_indices=[]
exl_indices=[]
content=[]
i = 0
for line in file:
if 'allow' in line:
allow_indices.append(i)
if '!' in line:
exl_indices.append(i)
content.append(line)
i += 1
file = open('text.txt','r')
base=''
formatted=''
for i in range(0,allow_indices[0]):
base+= content[i]
close_index=0
for i in allow_indices:
new_base = base+content[i]
formatted+=new_base.replace('\n','')+'\n'
for j in range(i+1,exl_indices[close_index]-1):
formatted+=new_base.replace('\n','')+content[j].replace('\n','')+'\n'
close_index+=1
print formatted
我将以下内容用作text.txt文件的内容:
control-plane
management-plane
inband
interface all
allow xy
address x.x.x.x
address y.y.y.y
!
allow b
address b.b.b.b
!
!
!
结果如下:
control-plane management-plane inband interface all allow xy
control-plane management-plane inband interface all allow xy address x.x.x.x
control-plane management-plane inband interface all allow xy address y.y.y.y
control-plane management-plane inband interface all allow b
control-plane management-plane inband interface all allow b address b.b.b.b