Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iptables remove specific rules by comment

I need to delete some rules with same comment.

For example I have rules with comment = "test it", so i can get list of them like this:

sudo iptables -t nat -L | grep 'test it'

But how can i delete all PREROUTING rules with comment 'test it'?

UPD: As @hek2mgl said, i can do something like this:

sudo bash -c "iptables-save > iptables.backup"
sed -i '/PREROUTING.*--comment.* "test it"/d' iptables.backup
sudo iptables-restore < iptables.backup
sudo rm iptables.backup

But between save and restore could be changes in iptables, so after restore there will be problems =/

like image 283
Suvitruf - Andrei Apanasik Avatar asked Jan 09 '23 17:01

Suvitruf - Andrei Apanasik


2 Answers

You can use the following command:

iptables-save | sed -r '/PREROUTING.*comment.*test it/s/-A/iptables -D/e'

iptables-save will return iptables commands that can be executed to return the current state of the firewall after a reboot or whatever.

Meaning it will contain lines like:

...
-A PREROUTING -p tcp -m tcp --dport 25 -j ACCEPT -m comment --comment "test it"
...

The sed command searches for lines containing PREROUTING.*comment.*test it (should be good enough) and prepends the term iptablesplus replaces -A by -D since -D deletes a rule. The result of the replacement operation get's then executed using the e command. The e command is a GNU extension to sed.


Note: If you want to print the command in addition to simply executing it you can use s/-A/iptables -D/pe.

like image 172
hek2mgl Avatar answered Jan 15 '23 20:01

hek2mgl


Yet another way to Remove by comment:

NOWRULES=$(iptables --line-number -nL INPUT | grep comment_here | awk '{print $1}' | tac)
for rul in $NOWRULES; do     /sbin/iptables -D INPUT $rul; sleep 0.1; done
like image 23
Zagfai Avatar answered Jan 15 '23 20:01

Zagfai