Iptables remove specific rules by comment

Suvitruf - Andrei Apanasik picture Suvitruf - Andrei Apanasik · Mar 15, 2015 · Viewed 7.1k times · Source

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 =/

Answer

hek2mgl picture hek2mgl · Mar 15, 2015

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.