I need to add a rule to iptables to block connections to a tcp port from the Internet.

Since my script may be called multiple times and there is not a script to delete the rule, I want to check if an iptables rule already exists before inserting it - otherwise there will be a lot of dup rules in the INPUT chain.

How can I check if an iptables rule already exists?

link|improve this question
feedback

migrated from stackoverflow.com Nov 22 '11 at 3:14

This question came from our site for professional and enthusiast programmers.

1 Answer

Just list and search for it?

iptables --list | grep $ip

... or however you have the rule specified. If you use grep -q it won't output anything, and you can just check the return value with $?

link|improve this answer
2  
I would suggest iptables-save|grep $ip instead as it is a more easily parseable format, especially in a script. You can check the exact syntax of the command too if you want. – Garrett Nov 22 '11 at 4:21
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.