【发布时间】:2019-11-15 04:00:49
【问题描述】:
我正在编写一个 python 脚本来从文件中 grep 字符串并以以下格式在 csv 文件中显示输出
输入文件(result_EPFT_config_device):
Hostname SIM-MPL-LTE-PE-RTR-134
loopback 22.13.7.34
lpts punt excessive-flow-trap
penalty-rate arp 10
penalty-rate icmp 50
penalty-rate igmp 50
penalty-rate ip 100
exclude interface Bundle-Ether6
exclude interface Bundle-Ether8
exclude interface Bundle-Ether15
exclude interface Bundle-Ether16
exclude interface Bundle-Ether53
exclude interface TenGigE0/0/1/1
exclude interface TenGigE0/1/1/0
exclude interface Bundle-Ether6.2
exclude interface Bundle-Ether6.4
exclude interface Bundle-Ether8.2
exclude interface Bundle-Ether8.4
exclude interface Bundle-Ether16.2
exclude interface Bundle-Ether16.4
exclude interface Bundle-Ether53.2
exclude interface TenGigE0/0/1/3.100
exclude interface TenGigE0/0/1/3.102
exclude interface TenGigE0/0/1/3.103
exclude interface TenGigE0/0/1/3.104
exclude interface TenGigE0/1/1/0.100
exclude interface GigabitEthernet0/0/0/1
exclude interface GigabitEthernet0/0/0/6
exclude interface GigabitEthernet0/0/0/9
dampening.
non-subscriber-interfaces
report-threshold 10
下面是我目前准备的python脚本。只能grep字符串并打印出来
import sys
import telnetlib
import os
import subprocess
import re
import csv
fh = open("result_EPFT_config_device", "r")
fh1 = open("testingAjay", "w+")
line = fh.readlines()
for lines in line:
if re.search("(lpts punt excessive-flow-trap)", lines):
m = (lines.split(' '))
print m[0], m[1], m[2]
if re.search("(penalty-rate arp)", lines):
n = (lines.split(' '))
print n[0], n[1], n[2]
if re.search("(penalty-rate icmp)", lines):
a = (lines.split(' '))
print a[0], a[1], a[2]
if re.search("(penalty-rate igmp)", lines):
b = (lines.split(' '))
print b[0], b[1], b[2]
if re.search("(penalty-rate ip)", lines):
c = (lines.split(' '))
print c[0], c[1], c[2]
if re.search("(dampening)", lines):
c = (lines.split(' '))
print c[0]
if re.search("(non-subscriber-interfaces)", lines):
c = (lines.split('-'))
print c[0], c[1], c[2]
if re.search("(report-threshold 10)", lines):
c = (lines.split(' '))
print c[0], c[1]
我的脚本输出:
lpts punt excessive-flow-trap
penalty-rate arp 10
penalty-rate icmp 50
penalty-rate igmp 50
penalty-rate ip 100
dampening.
non subscriber interfaces
report-threshold 10
现在我想把输出放在 csv 文件中,如下所示
Hostname|loopback|lpts punt excessive-flow-trap|penalty-rate arp|penalty-rate icmp|penalty-rate igmp|penalty-rate ip|dampening|non-subscriber-interfaces|report-threshold
SIM-MPL-LTE-PE-RTR-134|1.1.1.1|yes|10|50|50|100|Yes|Yes|10
NDL-MPL-PE-RTR-195|2.2.2.2|No|No|No|20|50|NO|20Yes
如上图所示,列lpt spunt overflow trap如果存在于输入文件中,则必须标记为YES,否则标记为NO。 阻尼列和非订阅者界面列
需要类似的逻辑你能帮我实现如上所示的csv格式的require输出
【问题讨论】:
-
嘿,介意我用python3回答吗?
-
您应该为行中的所有数据创建列表或字典,使用您的代码填充它,并在您获得下一个
Hostname时在csv中写入行 -
看来您可以在没有正则表达式的情况下对其进行测试 - 即。
if lines.startswith('lpts punt excessive-flow-trap'):