安装

1
pip install --upgrade python-iptables

引用

1
2
3
4
5
import iptc
# iptables 的表
table = iptc.Table(iptc.Table.FILTER)
# iptables 的链
chain = iptc.Chain(table, "INPUT")

理论

python-iptables中,操作的对象是一个Rule

rule = iptc.Rule()

rule有一些属性

  • in_interface 网络接口,如eth0
  • src 源ip地址,如"192.168.1.0/255.255.255.0"
  • protocol 协议,如tcp udp

有了Rule以后,需要知道是什么样的规则,于是就有了Match

1
2
3
4
match = iptc.Match(rule,'tcp')
rule.add_match(match)
# 跟下面的表达式等价
match = rule.add_match('tcp')

match也同样有一些属性

  • dport 目的端口,如match.dport = ‘80’
  • sport 来源端口
  • mark 对数据包的标记,如match.mark = ‘0xff’

当规则和条件都有了以后,就需要对这个包做一些动作:

1
2
3
4
target = iptc.Target(rule, "DROP")
rule.target = target
# 跟下面的表达式等价,动作可以是DROP也可以是ACCEPT
target = rule.create_target("DROP")

实战

查看当前的iptables列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import iptc
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,
print "Matches:",
for match in rule.matches:
print "dport:", match.dport, "sport:",match.sport,
print "Target:",
print rule.target.name,
print "Counter:",
print rule.get_counters()
print "======================="

在INPUT表中新增/删除一条规则

iptables -A OUTPUT -p tcp –sport 1800

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import iptc
table = iptc.Table(iptc.Table.FILTER)
chain = iptc.Chain(table, "OUTPUT")

rule = iptc.Rule()
rule.protocol = "tcp"
match = iptc.Match(rule,'tcp')
match.protocol = 'tcp'
match.sport = "1800"
rule.add_match(match)
target = iptc.Target(rule, "ACCEPT")
rule.target = target
chain.insert_rule(rule)
#chain.delete_rule(rule)
table.commit()

清空规则和清空计数器

1
2
3
4
5
6
7
import iptc
table = iptc.Table(iptc.Table.FILTER)
input = iptc.Chain(table, "INPUT")
# 清空计数器
input.zero_counters()
# 清空规则
input.flush()