python - 如何使用 python-iptables 编写特定的 iptables 规则

标签 python iptables

我正在尝试使用 python-iptables 编写脚本来设置某些规则。我弄清楚了如何设置规则以允许所有连接和拒绝所有连接,但我需要弄清楚如何编写规则以允许已建立的连接。

例如,我需要使用 python-iptables 编写以下规则:

iptables -A INPUT  -m state --state     RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

如果有人有第一手知识或知道编写上述或类似规则的好资源,我将不胜感激。提前致谢!

这是成品。我计划添加更多规则选项,以允许用户根据需要允许 http/s 等连接。感谢您提供的所有帮助。

import iptc

def dropAll():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "eth+"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)

def allowLoopback():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "lo"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.insert_rule(rule)

def allowEstablished():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
    rule = iptc.Rule()
    match = rule.create_match('state')
    match.state = "RELATED,ESTABLISHED"
    rule.target = iptc.Target(rule, 'ACCEPT')
    chain.insert_rule(rule)

dropAll()
allowLoopback()
allowEstablished()

最佳答案

我没有尝试过使用 python-iptables,但看起来你需要这样的东西:

rule = iptc.Rule()
match = rule.create_match('state')
match.state = 'RELATED,ESTABLISHED'
match.target = iptc.Target('ACCEPT')

chain = iptc.Chain(iptc.Table.(iptc.Table.FILTER), "INPUT")
chain.insert_rule(rule)

等等。

关于python - 如何使用 python-iptables 编写特定的 iptables 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20734319/

相关文章:

python - 增加物体移动的速度(Tkinter)

python - python中整数比较的时间复杂度

IPTABLES: ping 和 wget 可以工作,但不能

ubuntu - 将 Kubernetes 网络路由更改为互联网

python - 如何在 anaconda spyder 中更改 python 版本

python - 方法分配和对象

python - Django 中 Jinja 的标签 'raw' 抛出错误 - 'Did you forget to register or load this tag?'

bash - docker 无法指定容器连接

linux - 有没有办法让非 root 进程绑定(bind)到 Linux 上的 "privileged"端口?

linux路由特定机器流量抛出特定输出接口(interface)