以声明的方式使用iptables
declarative-iptables的Python项目详细描述
简单表格
在linux上管理iptables的简单接口
管理iptables最困难的部分是,它们是从许多不同方向不断变化的数据的中心部分。因为它的状态无法保证,所以对它进行简单的修改可能会产生不希望的后果。该项目旨在通过制作另一个iptables接口来解决这个问题。
此接口旨在声明性。这个包定义了所需的状态,而不是直接发布对iptables的更改。重要的是,在任何给定的时间,表的外观都不重要,相反,目标是最终得到它应该是什么样子
另外,由于不知道其他系统做了什么更改,所以未声明的任何表和规则都将保持不变
示例
import iptables
plan = iptables.Plan()
# this will delete an existing table and create it from scratch
berto_chain = plan.add_chain('OPENVPN_BERTO')
# rules are added with a default priority of 50
berto_chain.add_rule(iptables.Rule('-o tun0 -s 192.168.2.2 -d 192.168.1.1 -j ACCEPT'))
# this will get an existing table and create it if it does not exist
openvpn_chain = plan.get_chain('OPENVPN')
# rules with higher number priority get added to the chain first
# when updating an existing chain, rules already in the chain get a priority of 70.
# being added is compared to existing rules and will be added if missing or left alone.
openvpn_chain.add_rule(iptables.Rule('-o ! tun0 -j RETURN', priority=100))
openvpn_chain.add_rule(berto_chain.jump)
# make necessary changes to achieve the desired outcome
plan_execute()