非常に長い間引き出された質問に対するお詫び。
設定ファイルを読み込んで、ルールのリストを取得しようとしています。ConfigParserを使用してこれを実行しようとしましたが、標準の構成ファイルではありません。このファイルには、セクションヘッダーとトークンは含まれていません。
すなわち
configセクションa
何かを他の何かに設定します
configサブセクションa
これをその
次の
終わりに設定しますconfigファイアウォールポリシー
編集
76setsrcintf "There"
set dstintf "Here"
set srcaddr "all"
set dstaddr "all"
set action accept
set schedule "always"
set service "TCP_5600"
next
edit 77
set srcintf "here"
set dstintf "there "
set srcaddr" all "
set dstaddr" all "
set action accept
set schedule" always "
set service" PING "
next
end
ConfigParserを機能させる方法がわからなかったので、ファイルを反復処理しようと思いましたが、残念ながらプログラミングスキルがあまりないため、行き詰まりました。私はこれを本来よりも複雑にしていると本当に思います。これが私が書いたコードです。
class Parser(object):
def __init__(self):
self.config_section = ""
self.config_header = ""
self.section_list = []
self.header_list = []
def parse_config(self, fields): # Create a new section
new_list = []
self.config_section = " ".join(fields)
new_list.append(self.config_section)
if self.section_list: # Create a sub section
self.section_list[-1].append(new_list)
else: self.section_list.append(new_list)
def parse_edit(self, line): # Create a new header
self.config_header = line[0]
self.header_list.append(self.config_header)
self.section_list[-1].append(self.header_list)
def parse_set(self, line): # Key and values
key_value = {}
key = line[0]
values = line[1:]
key_value[key] = values
if self.header_list:
self.header_list.append(key_value)
else: self.section_list[-1].append(key_value)
def parse_next(self, line): # Close the header
self.config_header = []
def parse_end(self, line): # Close the section
self.config_section = []
def parse_file(self, path):
with open(path) as f:
for line in f:
# Clean up the fields and remove unused lines.
fields = line.replace('"', '').strip().split(" ")
if fields[0] == "set":
pass
elif fields[0] == "end":
pass
elif fields[0] == "edit":
pass
elif fields[0] == "config":
pass
elif fields[0] == "next":
pass
else: continue
# fetch and call method.
method = fields[0]
parse_method = "parse_" + method
getattr(Parser, parse_method)(self, fields[1:])
return self.section_list
config = Parser().parse_file('test_config.txt')
print config
私が探している出力は次のようなものです。
[['section a'、{'something':'to something'}、['subsection a'、{'this':'to that'}]]、['firewall policy'、['76'、{ 'srcintf':'There'}、{'dstintf':'Here'}{etc。}{etc。}]]]
これが私が得たものです
[['セクションa']]
編集
私は現在の場所を反映するために上記を変更しました。期待する出力を得るのにまだ問題があります。私はリストを正しく理解できないようです。