User Tools

Site Tools


docu:snippet:net:pyth_iptables_once

iptables-once, never add repeated iptables again!


Never add repeated iptables rules again, this snippet will help you wrap around iptables to achieve that!

iptables-once.py
#!/usr/bin/python3
import sys
import os
 
def main():
        args = sys.argv[1:]
        if args[0] in ['-A', '-I', '-D']:
                process_iptables(0, args)
        elif args[2] in ['-A', '-I', '-D']:
                process_iptables(2, args)
 
def process_iptables(ind, args):
        oa = args[ind]
        if oa in ['-A', '-I']:
                targs = args.copy()
                targs[ind] = '-C'
                i = 0
                while i < 60:
                        res = os.system('iptables '+' '.join(targs)+' 2>/dev/null')
                        if res == 0:
                                break
                        os.system('iptables '+' '.join(args))
                        i += 1
        elif oa == '-D':
                targs = args.copy()
                targs[ind] = '-C'
                i = 0
                while i < 60:
                        res = os.system('iptables '+' '.join(targs)+' 2>/dev/null')
                        if res != 0:
                                break
                        os.system('iptables '+' '.join(args))
                        i += 1
 
if __name__ == '__main__':
        main()
docu/snippet/net/pyth_iptables_once.txt · Last modified: 2020/04/27 17:49 by admin