3

如果我有这样的文本文件:

FastEthernet3/1
ip address 0.0.0.0
enable portfast

FastEthernet3/2
ip address 0.0.0.0
enable portfast

FastEthernet3/3
ip address 0.0.0.0

FastEthernet3/4
ip address 0.0.0.0

我想打印出没有启用portfast的接口。我如何在python中打印这个?

我有以下代码:

import os
import sys

root = "path to text file like the example above"

os.chdir(root)

current2 = os.getcwd()

print ("CWD = ", current2,"\n")


file = sys.argv[1]

f = open(file)
contents = f.read()
f.close()
print ("Number of GigabitEthernet:",contents.count("interface GigabitEthernet"))
print ("Number of FastEthernet:",contents.count("FastEthernet"))


x = open(file)
string1 = "enable portfast"
for line in x.readlines():
    if line.startswith(string1)
        print (line)
filehandle.close()

所以我可以找到启用 portfast 的行并打印它,但我希望它打印更多行,所以我知道女巫接口启用了 portfast。

4

6 回答 6

2

如果每个接口定义都以 string 开头"FastEthernet",你可以contents用那个字符串分割你的:

interfaces = contents.split("FastEthernet"):
for interface in interfaces:
    if "enable portfast" in interface:
        print "FastEthernet" + interface

编辑:基于 Alexanders 解决方案,如果总是有一个空白行分隔接口,只需声明interfaces如下:

interfaces = contents.split("\n\n")

...并将打印语句更改为print interface仅。

于 2012-09-20T11:19:49.907 回答
2

无法返回文件,因此最好的解决方案是跟踪前面的行并在 portFast 匹配时打印它们。

编辑以包含解决方案:(感谢亚历山大)

import re
pinterfaces = re.compile("\r?\n\r?\n").split(contents)
# pinterfaces = ['FastEthernet3/1...', 'FastEthernet3/2...', ...]
for pinterface in pinterfaces:
  if "enable portfast" in pinterface:
    print pinterface
于 2012-09-20T11:16:09.383 回答
2

基于空行分隔的接口拆分:

import re
pinterfaces = re.compile("\r?\n\r?\n").split(contents)
# pinterfaces = ['FastEthernet3/1...', 'FastEthernet3/2...', ...]
for pinterface in pinterfaces:
  if "enable portfast" in pinterface:
    print pinterface

FastEthernet3/1
ip address 0.0.0.0
enable portfast
FastEthernet3/2
ip address 0.0.0.0
enable portfast
于 2012-09-20T11:29:06.810 回答
0

感谢 Alexander,它现在可以工作了 :) 唯一的问题是我的文本文件与示例有点不同。它看起来像这样:

FastEthernet3/1
ip address 0.0.0.0
enable portfast
!
FastEthernet3/2
ip address 0.0.0.0
enable portfast
!
FastEthernet3/3
ip address 0.0.0.0
!
FastEthernet3/4
ip address 0.0.0.0

所以我不得不更换!首先有一个空白,然后它起作用了:)

import re
contents2 = contents.replace("!","")
pinterfaces = re.compile("\n\n").split(contents2)
# pinterfaces = ['FastEthernet3/1...', 'FastEthernet3/2...', ...]
for pinterface in pinterfaces:
  if "enable portfast" in pinterface:
    print (pinterface)
于 2012-09-20T12:28:26.743 回答
0
with open('test.txt', 'r') as in_file:
    lines = in_file.readlines()

for i,v in enumerate(lines):
    #print i,v
    if v.strip() == 'enable portfast':
        print lines[i-2].strip()
        print lines[i-1].strip()
        print lines[i].strip()

这打印出来:

FastEthernet3/1
ip address 0.0.0.0
enable portfast
FastEthernet3/2
ip address 0.0.0.0
enable portfast
于 2012-09-20T11:28:11.783 回答
-1

尝试将所有设备分别解析为字典数组,如下所示:

[{"device_name":"FastEthernet/1","address":"1.0.0.0", "portfast": True}]

然后您可以遍历此哈希并打印具有该portfast值的项目的设备名称。

于 2012-09-20T11:13:58.583 回答