New on LowEndTalk? Please Register and read our Community Rules.
All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.
All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.
Remove duplicate iptables rules?
I see I have some duplicate iptables rules on my server.
Is there a command/script to remove to remove duplicate rules automatically?
I found this script, but I don't trust it too much: http://elliottback.com/wp/iptables-bash-shell-cleanup-script/
Comments
A bash script to list your rules, echo them in to a file, run diff/sort on them, flush current rules and apply the clean set would be simple enough, drop me an email if you want, I could write you something fairly quick with a backup option just for confidence
@Freek i take it out of the control of any other Net services and handle iptables with my own scripts. Just my two
Isn't CSF a solution for this?
iptables-save
> /etc/iptables.conf
This I don't know.
iptables -F
iptables-restore < /etc/iptables.conf
Or just create an script with your rules and flush the rules at the start
Just comment out the duplicate rules in
/etc/sysconfig/iptables
and runservice iptables restart
Only if on an RHEL-based distro.
This is what I do on my servers works well. Can also use the script on what ever distro you install.
iptables-save | uniq | iptables-restore
Lol @ win
^^^^ that's what we use on a 24hr cron task.
Does uniq mess up the order of rules?
@t3k9 That won't work. Uniq only works if a line occurs twice in a row, which may not be the case in an iptables ruleset.
awk! awk!
iptables-save | awk ' !x[$0]++' | iptables-restore
Famous Awk One-Liners Explained: 43. Remove duplicate, nonconsecutive lines
| sort | uniq
fscking with the order of things in iptables-land ist verboten!
Indeed n_n
So, my first recommendation stays, just do an script ¬_¬
#!/usr/bin/perl open( my $iptablesSave, "-|", "iptables-save"); my @iptablesOrig; (@iptables) = <$iptablesSave>; close $iptablesSave; my @iptablesOut; foreach my $line (@iptablesOrig) { my $push = 1; foreach my $check (@iptablesOut) { if $check == $line { $push = 0; } } if $push == 1 { push $line, @iptablesOut; } } my $iptablesOut = join ("\n" @iptablesOut); open (my $iptablesRestore, "|-", "iptables-restore"); print $iptablesRestore $iptablesOut; close ($iptablesRestore);
No guarantees.
Done But as t3k9's command also works, so it's not necessary anymore. But if you want to show off your bash skills, feel free to do so
Works like a charm, thanks!
root@gunther:~# iptables-save | awk ' !x[$0]++' | iptables-restore
Bad argument
*filter' Error occurred at line: 14 Try
iptables-restore -h' or 'iptables-restore --help' for more information.Haha that's the magic
Wasn't planning on commenting out 40 duplicate lines.
nvm