【问题标题】:Is there a python interface to iptables?iptables 有 python 接口吗?
【发布时间】:2011-08-19 00:08:01
【问题描述】:

我正在尝试通过 python 检索系统上配置的当前 iptables 链。如果我 strace iptables 命令,它会输出:

strace iptables -L INPUT
socket(PF_INET, SOCK_RAW, IPPROTO_RAW)  = 3
getsockopt(3, SOL_IP, 0x40 /* IP_??? */, "filter\0\377`\2\351\1\0\210\377\377\210}\313\276\0\210\377\377\354\206\0\201\377\377\377\377"..., [84]) = 0

此处的完整输出:http://pastebin.com/e7XEsaZV

在 python 中,我创建了套接字 obj 并尝试调用 getsockopt 并出现错误:

>>> s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
>>> s.getsockopt(socket.SOL_IP, 0x40)
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    s.getsockopt(socket.SOL_IP, 0x40)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 22] Invalid argument
>>>
>>> s = socket.socket(2, socket.SOCK_RAW, socket.IPPROTO_RAW)
>>> s.getsockopt(socket.SOL_IP, 0x41)
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    s.getsockopt(socket.SOL_IP, 0x41)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 22] Invalid argument
>>> 

这不可能吗?

【问题讨论】:

  • 由于您的问题是关于python,我删除了C 标签。
  • 我似乎错过了iptables 和您的python 套接字之间的关系......也许是一个愚蠢的问题,但您介意详细说明两者之间的关系吗?
  • @Mike 我可能遗漏了一些重要的东西我只是想在 Python 中模拟 iptables 命令并查看 iptables 命令上的 strace,我假设(我不是真正的开发人员)是如何检索内核中配置的当前 iptables。我可能错了,但我没有看到任何 ioctls 等。
  • 当您说模拟 iptables 时,您具体要在 python 中模拟什么?

标签: python linux sockets networking iptables


【解决方案1】:

错误 22 的原因很明显。 getsockopt() 类型为IPT_SO_GET_INFO 的调用需要指向struct ipt_getinfo 的指针的第三个参数。该结构在我的 Linux 中包含 /usr/include/linux/netfilter_ipv4/ip_tables.h 文件。

此外,还有更多要求。为getsockopt() 调用提供的缓冲区大小需要与结构的大小相匹配,在我的机器中为 84 字节。为什么这个调用真的失败是结构成员.name 必须指明你有兴趣查询哪个表的要求。表名未指定大小和随机字节将导致此错误 22.

使用 Python,最终这一切都失败了,因为没有用于输入用户定义字节作为 getsockopt() 的参数的 API。假设IPT_SO_GET_INFO 可以工作,那么自然下一步就是读取带有IPT_SO_GET_ENTRIES 的表的所有链,这在Python 中也是不可能的。 Python 的 getsockopt() 不允许缓冲区大于 1024 字节。在任何使用 IPtables 的真实 Linux 中,链式规则很容易超过 1 KiB 的限制。

关于如何阅读 IPtables 规则的一个很好的 C 示例位于 https://github.com/mozilla/rr/blob/master/src/test/netfilter.c

【讨论】:

    【解决方案2】:

    你见过python-iptables吗?

    Python-iptables 为 Linux 下的 iptables 提供 python 绑定。与 iptables 的互操作性是通过使用 iptables C 库(libiptc、libxtables 和 iptables 扩展)实现的,而不是调用 iptables 二进制文件并解析其输出。

    【讨论】:

    • 我发誓我在尝试重新发明轮子之前寻找过这个。再次感谢您。
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2010-12-16
    相关资源
    最近更新 更多