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 =/
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 iptables
plus 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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With