2016-12-14 23:18:16 +00:00
|
|
|
#!/usr/bin/env python
|
2017-02-22 13:41:58 +00:00
|
|
|
# Python helper tool to add IPtables rule using the iptc library. This must
|
|
|
|
# of course run as root for iptc to work.
|
2016-12-14 23:18:16 +00:00
|
|
|
|
|
|
|
from argparse import ArgumentParser
|
|
|
|
from pprint import pprint as pp
|
|
|
|
|
|
|
|
import iptc
|
|
|
|
|
|
|
|
parser = ArgumentParser()
|
|
|
|
|
|
|
|
parser.add_argument('--chain', required=True)
|
|
|
|
parser.add_argument('--protocol', required=True)
|
|
|
|
parser.add_argument('--src-ip', required=True)
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
table = iptc.Table(iptc.Table.MANGLE)
|
|
|
|
chain = iptc.Chain(table, args.chain)
|
|
|
|
|
|
|
|
# Check if rule exists
|
|
|
|
for rule in chain.rules:
|
|
|
|
src_ip = rule.src
|
2016-12-22 15:01:15 +00:00
|
|
|
if src_ip.startswith(args.src_ip) and rule.protocol == args.protocol:
|
2016-12-14 23:18:16 +00:00
|
|
|
print('Rule exists')
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
rule = iptc.Rule()
|
|
|
|
rule.src = args.src_ip
|
|
|
|
rule.protocol = args.protocol
|
|
|
|
rule.target = iptc.Target(rule, 'RETURN')
|
|
|
|
chain.insert_rule(rule)
|