iptables.py runs on python3
[tests.git] / system / template-qemu / iptables.py
1 #!/usr/bin/python3
2
3 import sys
4 import re
5
6
7 def main():
8     with open(sys.argv[1]) as fin, open(sys.argv[2], "w") as fou:
9         ip = sys.argv[3]
10
11         found = False
12         lo_matcher = re.compile("\A(?P<left>.+)\s+-i\s+lo\s+-j\s+ACCEPT")
13         # what comes out of iptables-save has short-options syntax
14         ip_matcher = re.compile(".*-(s|d) %s" % ip)
15         for line in fin.readlines():
16             attempt = lo_matcher.match(line)
17             if attempt:
18                 fou.write(line)
19                 # open-up for this IP
20                 fou.write("%s -s %s -j ACCEPT\n" % (attempt.group('left'), ip))
21                 fou.write("%s -d %s -j ACCEPT\n" % (attempt.group('left'), ip))
22                 found = True
23             else:
24                 attempt = ip_matcher.match(line)
25                 # do not rewrite old lines for this ip
26                 if not attempt:
27                     fou.write(line)
28     if found:
29         return 0
30     else:
31         return 1
32
33
34 if __name__ == '__main__':
35     exit(main())