【发布时间】:2021-03-17 03:52:09
【问题描述】:
有一个 txt 文件,我需要在安全、防火墙下获取值,仅捕获规则号、源、目标端口和协议,如果缺少任何键需要针对没有值的键将默认文本打印为“任何” ,同样需要在文件中获取所述键的数据
文本文件数据
security {
firewall {
global-state-policy {
icmp
tcp
udp
}
name Local {
default-action drop
default-log
description "Local firewall rules."
rule 9 {
action accept
source {
address AccountFront
}
}
rule 10 {
action accept
source {
address SoftLayerBack
}
}
rule 11 {
action accept
source {
address SoftLayerFront
}
}
rule 20 {
action accept
description "Allow ping reply"
icmp {
type 0
}
------
------etc
需要这种形式的输出,
RULE_NAME{
9
SOURCE - 'any' if value doesn't exists
DESTINAION
PORT
POROTCOL
10
SOURCE
DESTINAION
PORT
POROTCOL
11
....
}
我编写了以下代码,但它返回空列表。 请帮忙
name, rule, address, destination, port, protocol= [''] * 6
access_list = []
with open(path + "mci_vyatta_config.txt", 'r') as fh:
for line in fh:
line = line.strip()
if line:
line_to_array = line.split(' ')
if line == "firewall;":
if line.startswith('name '):
name = line_to_array[1]
print(name)
#to_zone = line_to_array[3]
elif line.startswith('rule '):
rule = line_to_array[1]
elif line.startswith('address '):
address = line_to_array[1].replace(";", "")
elif line.startswith('destination '):
destination = line_to_array[1].replace(";", "")
elif line.startswith('port '):
port = line_to_array[1].replace(";", "")
elif line.startswith('protocol '):
port = line_to_array[1].replace(";", "")
elif line.startswith('then {'):
line = next(fh).strip() # Gets next line in file
access_list.append({'NAME': name,
'RULE': rule,
'SOURCE': address,
'DESTINATION': destination,
'PORT': port,
'PROTOCOL': protocol})
name, rule, address, destination, port, protocol= [''] * 6
return access_list
access_list = read_config("/home/Fathima/workspace/training/")
print(access_list)
有些规则只有源即地址,有些只有端口或协议,如果源、目标端口和协议值存在,我们需要打印值,否则需要显示关键字为'any'
rule 53 {
action accept
description "Allow inbound to Zabbix agent"
protocol tcp
source {
port ZBX_TCP
}
state enable
}
rule 60 {
action accept
description "Allow UDP ports from VPN peers"
destination {
port IPSecPorts
}
protocol udp
source {
address IPSecPeers
}
}
示例 - 对于规则 53,名称应打印为 53 作为规则名称,协议值应打印为 tcp,端口为 ZBX_TCP,由于未提及地址,因此应打印“任何”
【问题讨论】:
-
@Tahera--在您的示例文本文件中,我们如何将源、目标端口和协议信息与规则相关联?例如,规则 9 具有
{ action accept source { address AccountFront}在您的代码中,您也缺少函数定义行。 -
Func def 已添加到我的原始代码中,此处错过发布
-
已添加最后一节解释相同,请检查,谢谢@DarrylG
标签: python