[英]Is there a python interface to iptables?
我試圖通過 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
完整的 output 在這里: 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-iptables嗎?
Python-iptables 提供 python 綁定到 Linux 下的 iptables。 與 iptables 的互操作性是通過使用 iptables C 庫(libiptc、libxtables 和 iptables 擴展)實現的,而不是調用 iptables 二進制文件並解析其 output。
錯誤 22 的原因很明顯。 類型為IPT_SO_GET_INFO
的getsockopt()
調用需要指向struct ipt_getinfo
的指針的第三個參數。 該結構在我的 Linux 中包含文件,位於/usr/include/linux/netfilter_ipv4/ip_tables.h
。
此外,還有更多的要求。 為getsockopt()
調用提供的緩沖區大小需要與結構的大小相匹配,在我的機器中為 84 字節。 為什么這個調用真的失敗是 struct member .name
的要求必須表明你有興趣查詢哪個表。 表名未指定大小和隨機字節將導致此錯誤 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.Z4A8A08F09D37B7379564903348
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.