我正在尝试创建一个 Python 脚本,它将我们的 IPtables 配置转换为 YAML 文件中的多防火墙。我最初使用的是 pyyaml,但是后来发现这会删除我需要保留的所有评论,我发现 ruamel.yaml 可以用来保留评论,但是,我正在努力让它工作。
import sys
import io
import string
from collections import defaultdict
import ruamel.yaml
#loading the yaml file
try:
config = ruamel.yaml.round_trip_load(open('test.yaml'))
except ruamel.yaml.YAMLError as exc:
print(exc)
print (config)
# Output class
#this = defaultdict(list)
this = {}
rule_number = 200
iptables_key_name = "ha247::firewall_addrule::firewall_multi"
# Do stuff here
for key, value in config.items():
# Maipulate iptables rules only
if key == 'iptables::rules':
# Set dic withim iptables_key_name
this[iptables_key_name] = {}
for rule, rule_value in value.items():
# prefix rule with ID
new_rule =("%s %s" % (rule_number,rule))
rule_number = rule_number + 1
# Set dic within [iptables_key_name][rule]
this[iptables_key_name][new_rule] = {}
# Ensure we have action
this[iptables_key_name][new_rule]['action'] = 'accept'
for b_key, b_value in rule_value.items():
# Change target to action as rule identifier
b_key = b_key.replace('target','action')
# Save each rule and ensure we are lowrcase
this[iptables_key_name][new_rule][b_key] = str(b_value).lower()
elif key == 'ha247::security::enable':
this['ha247::security_firewall::enable'] = value
elif key == 'iptables::safe_ssh':
this['ha247::security_firewall::safe_ssh'] = value
else:
# Print to yaml
this[key] = value
# Write YAML file
with io.open('result.yaml', 'w', encoding='utf8') as outfile:
ruamel.yaml.round_trip_dump(this, outfile, default_flow_style=False, allow_unicode=True)
输入文件 (test.yaml)
---
# Enable default set of security rules
# Configure firewall
iptables::rules:
ACCEPT_HTTP:
port: '80'
HTTPS:
port: '443'
# Configure the website
simple_nginx::vhosts:
<doamin>:
backend: php-fpm
template: php-magento-template
server_name:
server_alias: www.
document_root: /var/www/
ssl_enabled: true
ssl_managed_enabled: true
ssl_managed_name: www.
force_www: true
result.yaml 的输出
ha247::firewall_addrule::firewall_multi:
200 ACCEPT_HTTP:
action: accept
port: '80'
201 HTTPS:
action: accept
port: '443'
ha247::security_firewall::enable: true
ha247::security_firewall::safe_ssh: false
simple_nginx::ssl_ciphers:
simple_nginx::vhosts:
<domain>:
backend: php-fpm
document_root: /var/www/
force_www: true
server_alias: www.
server_name: .com
ssl_enabled: true
ssl_managed_enabled: true
ssl_managed_name: www.
template: php-magento-template
这就是问题所在,您可以看到它已经更改了所有格式并删除了我们需要保留的注释,另一个问题是它删除了顶部的三个连字符,这将导致配置管理器无法读取文件。