Created
January 6, 2019 07:58
-
-
Save homoluctus/60da8b945029ee67401c75ccd76e8cc4 to your computer and use it in GitHub Desktop.
Manipulate iptables using python-iptables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import iptc | |
import ipaddress | |
def format_address(address): | |
""" | |
Support IPv4 only yet. | |
Return IPv4 with prefix length (e.g. 192.168.0.1/32) | |
""" | |
if isinstance(address, (str, ipaddress.IPv4Address)): | |
try: | |
address = ipaddress.ip_network(address) | |
except ValueError: | |
raise | |
elif isinstance(address, ipaddress.IPv4Network): | |
pass | |
else: | |
raise TypeError | |
return address.with_prefixlen | |
def display_matches(matches=[]): | |
print("Match:", end=' ') | |
for match in matches: | |
for key, value in match.get_all_parameters().items(): | |
if isinstance(value, list): | |
value = ', '.join(value) | |
print("[{}] {}".format(key, value)) | |
def display_rule(rule): | |
print('+'*40) | |
print("Target:", rule.target.name) | |
print("Protocol:", rule.protocol) | |
print("Source address:", format_address(rule.src)) | |
print("Destination address:", format_address(rule.dst)) | |
display_matches(rule.matches) | |
print('+'*40) | |
def delete_rule(chain, rule): | |
chain.delete_rule(rule) | |
if __name__ == '__main__': | |
# Create rule | |
rule1 = iptc.Rule() | |
rule1.out_interface = 'eth0' | |
rule1.dst = "192.168.0.1" | |
rule1.protocol = 'icmp' | |
match_for_rule1 = rule1.create_match('icmp') | |
match_for_rule1.icmp_type = 'echo-request' | |
rule1.create_target('DROP') | |
rule2 = iptc.Rule() | |
rule2.out_interface = 'eth0' | |
rule2.dst = "192.168.0.2" | |
rule2.protocol = 'icmp' | |
match_for_rule2 = rule2.create_match('icmp') | |
match_for_rule2.icmp_type = 'echo-reply' | |
rule2.create_target('DROP') | |
# Create chain | |
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT') | |
# Apply rule to chain | |
chain.insert_rule(rule1) | |
chain.insert_rule(rule2, position=1) | |
for rule in chain.rules: | |
try: | |
display_rule(rule) | |
except: | |
from traceback import print_exc | |
print_exc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment