python - 无法向 iptables 添加规则,没有提交任何内容

标签 python linux python-3.x iptables python-iptables

根据documentation:rules ,执行以下操作应该向 iptables 规则列表添加一个简单的规则:

rule = iptc.Rule()
rule.src = "127.0.0.1"
rule.protocol = "udp"
rule.target = rule.create_target("ACCEPT")
match = rule.create_match("comment")
match.comment = "this is a test comment"
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
chain.insert_rule(rule)

但是,运行此示例会导致新规则绝对为零。
我正在通过以下方式验证这一点:

iptables -L --line-number

在提交错误问题之前,我想知道是否有其他人遇到过此问题,如果遇到过,您是如何解决的。

为了安全起见,我以 root 身份运行所有内容,我还尝试通过运行文档同一部分中的另一个示例代码来验证规则:

table = iptc.Table(iptc.Table.FILTER)
for chain in table.chains:
    print ("=======================")
    print ("Chain ", chain.name)
    for rule in chain.rules:
        print ("Rule", "proto:", rule.protocol, "src:", rule.src, "dst:", \
                      rule.dst, "in:", rule.in_interface, "out:", rule.out_interface,)
        print ("Matches:")
        for match in rule.matches:
            print (match.name)
        print ("Target:"),
        print (rule.target.name)
print ("=======================")

(稍作修改以使用 Python3)。

这是为了确保自动提交没有问题,但结果仍然相同。 我还要指出它确实工作了一小段时间,大约为 iptables 添加了 3 个。执行 systemctl restart iptables 可能会奏效,但如果可能的话,我想 - 在我执行经典的旧“windows 技巧”重新启动之前弄清楚为什么会出错。 (journald/systemd 中没有提到任何关于 iptables 的内容)

最佳答案

由于@larsks 无法重现我进一步挖掘的问题。 似乎已执行系统更新(经典错误,我深表歉意)。

这导致加载的内核版本与 iptables 的内核模块不同,有一些修复程序使用 iptables 命令解决了这个问题,因此您仍然可以添加规则。

但是,使用库 python-iptables 不起作用。
实际的区别是什么超出了我的范围,我挖掘了一点但无法找到这会导致问题的地方。

不幸的是,在这种情况下重启机器是唯一(据我所知)解决此问题的方法。这是为了使加载的内核模块和安装的工具与它们正在使用的版本相匹配。

(另一种解决方案是保留旧的 iptables 命令和库,这意味着备份它们并将库指向备份的版本,直到可以重新启动)。

关于python - 无法向 iptables 添加规则,没有提交任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255170/

相关文章:

python - Decimal 类如何不可变?

python - 错误 'power iteration failed to converge within 100 iterations' ) 当我尝试使用 python networkx 汇总文本文档时

linux - 在后台 EC2 中运行 python 脚本

linux - Intel VMX中KVM如何调度多个VM?

python - 如何在 Python 中修复我的数据类的 TypeError?

django.core.cache.backends.base.InvalidCacheBackendError : Could not find backend 'django_redis.cache.RedisCache' : cannot import name 'six'

python - 如何在python中保存和恢复多个变量?

c++ - eclipse CDT : How to use GCC C++ compiler on C sources?

python - 我们如何确定属性属于实例还是类?

python - 从 pybind11 包装特征返回数组列表或元组