2016-06-14 74 views
0

我有一系列防火牆配置有一些非常糟糕的格式化(fortinet),我們正在嘗試將所有防火牆規則放入帶有相應信息的列和行的Excel電子表格中。我記得我們可以使用一個python模塊來做到這一點,但是我在導入時忘記了這個名稱....任何專家都可以提供一些指針?用於格式化文本文件的Python模塊

防火牆配置文件看起來是這樣的:

config firewall policy 1 
    edit eth1 
    set srcintf 33 
    set srcaddr 10.50.43.28 255.255.255.255 
    set dstintf 31 
    set dstaddr all 
    set schedule always 
    set service https 
    set action accept 
end 

config firewall policy 2 
    edit eth1 
    set srcintf 33 
    set srcaddr 10.50.45.28 255.255.255.255 
    set dstintf 31 
    set dstaddr all 
    set schedule always 
    set service https, ftp 
    set action accept 
end 

而最終的結果將是一個表(CSV文件)

Policy Name Source Address Destination Address Service Action 

1  10.50.43.28 255.255.255.255 all https accept 


2  10.50.45.28 255.255.255.255 all https, ftp accept 

非常感謝

+0

可能爲這樣的配置文件寫一個簡單的自定義分析器,但同時可能檢出這個工具[Fortinet Config Parse Tool v0.3](https://github.com/Fatal-Halt/FortiGate-Config-Parser) – davedwards

回答

1

您應該檢查:

  • Python's open()學習如何讀取和寫入文件
  • Python的字符串.format()學習如何格式的日誌,你想

這裏順便遵循什麼我想出了使用python3:

#!/usr/bin/env python3 
with open('log.txt', 'r') as log: 
    csv = 'Policy,Name Source Address,Destination Address,Service,Action\n' 
    policy_text = 'config firewall policy' 
    name_text = 'set srcaddr' 
    destination_text = 'set dstaddr' 
    service_text = 'set service' 
    action_text = 'set action' 

    def value(text, text_type): 
     return text.replace(text_type, '').strip() 

    for line in log.readlines(): 
     if policy_text in line: 
      policy = value(line, policy_text) 
     elif name_text in line: 
      name = value(line, name_text) 
     elif destination_text in line: 
      destination = value(line, destination_text) 
     elif service_text in line: 
      service = value(line, service_text) 
     elif action_text in line: 
      action = value(line, action_text) 
     elif 'end' in line: 
      csv = '{}"{}","{}","{}","{}","{}"\n'.format(
      csv, policy, name, destination, service, action) 

    with open('log.csv', 'w') as final_log: 
     print(csv, file=final_log)