是否有iptables的python接口?

问题描述 投票:14回答:2

我正在尝试通过python检索系统上配置的当前iptables链。如果我跟踪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 linux sockets networking iptables
2个回答
18
投票

您看过python-iptables吗?

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


0
投票

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

此外,还有更多要求。在我的计算机中,为getsockopt()调用指定的缓冲区大小必须与struct的大小匹配。为什么此调用真正失败的原因是结构成员.name must的要求,即您要查询哪个表。表名未指定大小和随机字节将导致此错误22。

使用Python,最终所有这些都会失败,因为没有API可以输入用户定义的字节作为getsockopt()的参数。假设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

© www.soinside.com 2019 - 2024. All rights reserved.