2

我想用 Python 写一个 iptables 脚本。而不是调用 iptables 本身,我想使用 python-iptables 包。但是,我很难设置一些基本规则。我想使用过滤器链来接受端口 1234 上的传入 TCP 流量。所以我写了这个:

import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()
target =  iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)

然而,当我运行它时,我把它抛给了我:

Traceback (most recent call last):
  File "testing.py", line 9, in <module>
    chain.insert_rule(rule)
  File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1133, in insert_rule
    self.table.insert_entry(self.name, rbuf, position)
  File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1166, in new
    obj.refresh()
  File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1230, in refresh
    self._free()
  File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1224, in _free
    self.commit()
  File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1219, in commit
    raise IPTCError("can't commit: %s" % (self.strerror()))
iptc.IPTCError: can't commit: Invalid argument
Exception AttributeError: "'NoneType' object has no attribute 'get_errno'" in <bound method Table.__del__ of <iptc.Table object at 0x7fcad56cc550>> ignored

有没有人有 python-iptables 的经验可以启发我做错了什么?

4

1 回答 1

2

哦,刚注意到这个。可以给github 上的最新头一个机会吗?我已经修复了大量的错误并更新了 python-iptables 以使用最新的 iptables 版本。如果您仍然遇到问题,请在github上开票。

肯定不太正确的一件事是您没有在规则中设置协议:

import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()

在此处设置协议,例如:

rule.protocol = 'tcp'

然后你应该没事:

target =  iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)
于 2013-02-07T10:07:13.847 回答