I want to delete a specific IPTable rule by searching for its specific comments.
If I add a rule using:
iptables -I INPUT -p udp -s xxx.xxx.xxx.xx -j DROP -m comment --comment 'DROP RULE'
How do I find the rule and then delete it but based on the comments ?
iptables -L --line-number | grep -i 'drop rule'
Should show the full rule, is there any way to get the line number and pass that to iptables -D INPUT x ?
Thanks
Tom's own comment is pretty much the answer. Assuming we are running as root here for these commands:
iptables -D INPUT $(iptables -L --line-number | grep "DROP RULE" | awk '{print $1}')
I've updated it to be a little more specific with the grep (match the case). If you have more than one rule with the same comment string, you can put it in a loop and delete them all as follows, though you do have to be careful and get the line number of each rule after the previous delete, as the line numbers are subject to change as rules are deleted:
while iptables -L --line-number | grep "DROP RULE" > /dev/null; do iptables -D INPUT $(iptables -L --line-number | grep "DROP RULE" | head -1 | awk '{print $1}'); done
Now, some things to be aware of. Make sure your comment string is unique, and only matches exactly the rules that you want. A comment like "anywhere" or "ESTABLISHED" is probably going to delete more rules than you want.
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